Decorator question
Lucasm
lordlucraft at gmail.com
Sun Oct 17 18:18:38 EDT 2010
On 16 Okt, 16:49, Peter Otten <__pete... at web.de> wrote:
> Lucasm wrote:
> > I have a decorator problem and hope someone is able to help me out/
> > assist me. Thanks in advance.
>
> > Suppose:
> > ### Begin some_library_module ###
>
> > def some_decorator(some_method):
> > def inner(an_arg, *args, **kwargs):
> > return some_method(an_arg, *args, **kwargs)
> > return inner
>
> > ### End some_library_module ###
>
> > ### Begin my_module ###
>
> > def my_decorator(some_method):
> > def inner(self, an_arg, *args, **kwargs):
> > self.do_something()
>
> At this point some_method() is just a Python function. You have to build a
> bound method or at least something that "knows" about self before you pass
> it on:
>
> bound_method = some_method.__get__(self)
> # bound_method = new.instancemethod(some_method, self)
> # bound_method = functools.partial(some_method, self)
> return some_decorator(bound_method)(an_arg, *args, **kwargs)
>
>
>
> > return inner
>
> > class My_Class(object):
> > @my_decorator
> > def my_method(self, an_arg, *args, **kwargs):
> > print self, an_arg
>
> > def do_something(self):
> > pass
>
> > ### End My_module ###
>
> >>>> My_Class().my_method('bla')
> > TypeError: my_method() takes at least 2 arguments (1 given)
>
> > `self` is lost in the process, because my decorator does use it and
> > the library's doesn't. I fail to find a way to keep self in the args
> > without modifying the library.
Thanks a lot! I didn't expect that it would be that easy :)
Regards,
Lucas
More information about the Python-list
mailing list