reckoner reckoner - 1 year ago 62
Python Question

how to dynamically generate methods for proxy class?

I have a object like:

class Foo(object):
def __init__(self,instance):
self.instance = instance


>>> instance = SomeOtherObject()
>>> f = Foo(instance)

I want to be able to do

>>> f.some_method()

and have the following call,

>>> f.instance.some_method()

For complicated reasons, I cannot simply chain the attributes as in the above. I need to dynamically create an instance function on
with the same function signature as the embedded
. That is, I need to do
and then dynamically create the
instance-method for the
instance when it is invoked that pushes
down to the embedded object

I hope that made sense. This is for Python 2.7. Any help appreciated.

Answer Source

Write a __getattr__() method for your proxy class. This will be called when an attribute is accessed that doesn't exist on your instance. Return your contained object's attribute of the same name (or a wrapper if you insist, but there's no need if you just want to call the contained object's method and don't need to do anything else). Bonus: works with data as well as callables.

def __getattr__(self, name):
    return getattr(self.instance, name)

Does not work with __ methods, however.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download