Decorator to inject function into __call__ of a class
Patrick Maupin
pmaupin at gmail.com
Sat Mar 13 12:03:00 EST 2010
On Mar 13, 10:38 am, Jon Clements <jon... at googlemail.com> wrote:
> On 13 Mar, 16:26, Patrick Maupin <pmau... at gmail.com> wrote:
>
>
>
> > On Mar 13, 10:19 am, Jon Clements <jon... at googlemail.com> wrote:
>
> > > What I'd like to achieve is something similar to:
>
> > > @inject(B):
> > > def some_function(a, b):
> > > pass # something useful
>
> > So, just typing at the keyboard here, you mean something like:
>
> > class InjectClass(object):
> > def __init__(self, func, *args, **kw):
> > self.func = func
> > self.args = args
> > self.kw = kw
> > def __call__(self):
> > self.func(*self.args, **self.kw)
>
> > Or exactly what are you looking for?
>
> > Pat
>
> Not quite.
>
> Let's say I have function 'F':
>
> def add(a, b): return a + b
>
> And a base class of 'C' which does all the __init__ stuff or
> whatever's needed,
> the function 'add' should return a new class __init__'d with a and b,
> but 'add'
> should be the __call__ of that instance.
>
> Hope that makes sense, and TY for your post,
>
> Jon.
Well, you could do it with a class. But if I'm understanding
correctly, maybe it's simpler than that:
>>> def inject(*args, **kw):
... def wrapper(func):
... def go():
... return func(*args, **kw)
... return go
... return wrapper
...
>>> @inject(20, 22)
... def add(a, b):
... return a + b
...
>>> add()
42
More information about the Python-list
mailing list