alex-bf
alex-bf

Reputation: 103

Add methods to a third party library class in Python

I'm using a third party library (PySphere) for a project I'm working on. PySphere provides a simple API to interact with VMware. This is a general problem though, not specific to this library.

A simple use of the library would be to get a VM object, and then perform various operations on it:

vm_obj = vcenter.get_vm_by_name("My VM")
vm_obj.get_status()
vm_obj.power_on()

I'd like to add a few methods to the vm_obj class. These methods are highly specific to the OS in use on the VM and wouldn't be worthwhile to commit back to the library. Right now I've been doing it like so:

set_config_x(vm_obj, args)

This seems really unpythonic. I'd like to be able to add my methods to the vm_obj class, without modifying the class definition in the third party library directly.

Upvotes: 4

Views: 828

Answers (1)

Jim Pivarski
Jim Pivarski

Reputation: 5974

While you can attach any callable to the class object (that is, vm_obj.__class__), that function would not be a method and would not have a self attribute. To make a real method, you can use the new module from the standard library:

vm_obj.set_config_x = new.instancemethod(callableFunction, vm_obj, vm_obj.__class__)

where callableFunction takes self (vm_obj) as its first argument.

Upvotes: 2

Related Questions