Decorator to inject function into __call__ of a class

Stephen Hansen apt.shansen at gmail.com
Sat Mar 13 14:02:34 EST 2010


On Sat, Mar 13, 2010 at 8:19 AM, Jon Clements <joncle at googlemail.com> wrote:

> The name 'some_function' is completely redundant -- don't need it,
> don't actually care about the function afterwards, as long as it
> becomes a __call__ of a 'B' *instance*.
>

Special methods are looked up on the class, not the instance, so you can't
dot his. However, from reading this thread, I think you're just a bit hung
up on naming: you don't need these random / arbitrary functions to be the
__call__ on an instance.

You need these functions to be called when said instance is called.

The easiest way to do that is simply define on the class:

def __call__(self, *args, **kwargs):
    self.func(*args, **kwargs)

Then while you are iterating over your list of a thousand functions and
making instances, just assign each instance's func attribute.

So,

for fn in [function_one, function_two, function_three, function_four]:
    inst = B()
    inst.func = fn

Now, if you really like the decorator syntax, sure:

>> def inject(klass):
...     def decorator(fn):
...             inst = klass()
...             inst.func = fn
...             return inst
...     return decorator
...
>>> class A:
...     def __init__(self):
...             pass
...     def __call__(self, *args, **kwargs):
...             self.func(*args, **kwargs)
...
>>> @inject(A)
... def test(mmm):
...     print mmm
...
>>> test
<__main__.A instance at 0x1004a4fc8>
>>> test("Hello")
Hello

Now, I don't -fully- understand what you're trying to do so this may not be
precisely the right thing, but you should be able to adapt the theory.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100313/d9fded8f/attachment.html>


More information about the Python-list mailing list