Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #49778 > unrolled thread

Re: Decorator help

Started byJoshua Landau <joshua.landau.ws@gmail.com>
First post2013-07-03 23:19 +0100
Last post2013-07-03 23:19 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Decorator help Joshua Landau <joshua.landau.ws@gmail.com> - 2013-07-03 23:19 +0100

#49778 — Re: Decorator help

FromJoshua Landau <joshua.landau.ws@gmail.com>
Date2013-07-03 23:19 +0100
SubjectRe: Decorator help
Message-ID<mailman.4185.1372889990.3114.python-list@python.org>
On 3 July 2013 23:09, Joseph L. Casale <jcasale@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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web