Decorator help

Joshua Landau joshua.landau.ws at gmail.com
Thu Jul 4 00:19:02 CEST 2013


On 3 July 2013 23:09, Joseph L. Casale <jcasale at activenetwerx.com> wrote:
> I have a set of methods which take args that I decorate twice,
>
> def wrapped(func):
>     def wrap(*args, **kwargs):
>         try:
>             val = func(*args, **kwargs)
>             # some work
>         except BaseException as error:
>             log.exception(error)
>             return []
>     return wrap
>
> def wrapped_again(length):
>     def something(func):
>         def wrapped_func(*args, **kwargs):
>             values = func(*args, **kwargs)
>             # do some work
>                 return values
>         return wrapped_func
>     return something
>
> So the methods wrapped are as follows:
>
> @wrapped_again(12)
> @wrapped
> def class_method(self, **kwargs):
>     #....
>
> Is it possible to get the name of the original method (class_method) from within wrapped_func inside wrapped_again?
> Thanks!

Normally  you'd want to use functools.wraps;

def wrapped(func):
    @functools.wraps
    def wrap(*args, **kwargs): ...
    return wrap

def wrapped_again(length):
    @functools.wraps
    def something(func): ...
    return something

@wrapped_again(12)
@wrapped
def class_method(self, **kwargs):
    ....

And then the name is "carried", as with docstrings.

If you don't want to do that, you'd need to use introspection of a
remarkably hacky sort. If you want that, well, it'll take a mo.



More information about the Python-list mailing list