Redirect method call and pass caller along automatically
<p>I'm building a modular app and I wanted all Objects of a certain type to be able to call a management object, and automatically have their own instance passed along.</p>

<p>Scenario:
My application consists of a framework and plugins that are being loaded at runtime.
One of these plugins provides functionality that operates in a separate contexts for each plugin. Simply put: It receives the instance of the caller plugin and only operates with data associated with this plugin.
In order to avoid confusion in the following description, lets refer to the callee as management object and to the caller as worker object.
There is going to be one management object and multiple plugins:<br>
Plugin + : 1 Management Object</p>

<p>I would like the worker object to be able to access the management funtionality, without the need to specify the instance of the worker instance explicitly in the parameter list.</p>

<p>Instead, I'd like the management methods to look, as if they belonged to the worker object - so that the passing of the caller argument is transparent and implicit.</p>

<p>One possibility would be, to register all new management methods with the worker class directly. However, I don't like this "namespace pollution". Instead, I'd like them to be accessible via an attribute so that the meaning is clear.</p>

<p>Keep in mind, that this behaviour is added at runtime, and I do not wish to modify the Plugin class itself. Also, multiple plugins may already have been instantiated at that time, but I need this to work for all current and future instances.</p>

<p>The idea I've come up with, is to combine the descriptor <code>__get__</code> and <code>__getattr__</code> methods in one object.</p>

<p>The <code>__get__</code> method will be used, to determine the instance of the caller.</p>

<p>The <code>__getattr__</code> method will be used, to dynamically wrap the method that is being supposed to be called from the management object.</p>

<p>The code I've come up with looks like this:</p>

<pre><code>my_management_object = getItHere()    
class Wrapper(object):
    def __init__(self):
        self._caller = None
     def __getattr__(self, name):
        method = getattr(my_management_object, name)
        def wrapper(*args, **kwargs):
            return method(self._caller, *args, **kwargs)
        return wrapper
     def __get__(self, caller, type):
        self._caller = caller
        return self
MyPluginClass._manage = Wrapper()
</code></pre>

<p>So now, I can do:</p>

<pre><code>obj = MyPluginClass()
obj._manage.doSomethingForMe()
#vs:
getMyManagementObject().doSomethingForMe(obj)
</code></pre>

<p>I have tested it and it seems to work.
I was wondering whether there are any pitfalls in this method or whether there are more pythonic ways to do this. I'm pretty new to the Descriptor stuff so I may have overlooked something.</p>

<p>Thanks in advance. (still looking for answers)</p>
