Decorator question

L

Lucasm

Hello,

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()
return some_decorator(some_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 ###
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.
 
P

Peter Otten

Lucasm said:
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)
 
L

Lucasm

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)

Thanks a lot! I didn't expect that it would be that easy :)

Regards,
Lucas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top