Propagating function calls

Chris Rebert clp2 at rebertia.com
Wed Feb 11 02:10:40 CET 2009


On Tue, Feb 10, 2009 at 5:02 PM, Noam Aigerman <noama at answers.com> wrote:
> Suppose I have a python object X, which holds inside it a python object Y.
> How can I propagate each function call to X so the same function call in Y

That'd be a method call actually, not a function call.

> will be called, i.e:
>
> X.doThatFunkyFunk()
>
> Would cause
>
> Y.doThatFunkyFunk()

Use a simple proxy (this will forward attribute accesses too, but that
doesn't usually matter and can be worked around if necessary):

class Delegator(object):
    def __init__(self, delegate):
        self.delegate = delegate
    def __getattr__(self, attr):
        return getattr(self.delegate, attr)

Example:
>>> a=Delegator([])
>>> a.append(5)
>>> a.delegate
[5]

Note that this won't forward the operator special methods (e.g. __add__).

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list