How to peek inside a decorated function

Hrvoje Niksic hniksic at xemacs.org
Sun Feb 15 05:27:36 EST 2009


Steven D'Aprano <steve at pearwood.info> writes:

> Suppose I have a function f() which I know has been decorated, but I don't
> have access to the original undecorated function any longer:
>
> def reverse(func):
>     def f(*args):
>         args = list(args)
>         args.reverse()
>         return func(*args)
>     return f
>
> def say(*args):
>     print args
>
> rsay = reverse(say)
> del say
>
> Is there any way to peek inside the decorated function rsay() to get access
> to the undecorated function say()?

This works in Python 2.5.2:

>>> rsay.func_closure[0].cell_contents
<function say at 0xb7e67224>

Of course, this applies only if you know there's only one free
variable, and you know that the decorator is in fact implemented with
a closure, and so on.

>>>> dir(rsay.func_closure[0])
> ['__class__', '__cmp__', '__delattr__', '__doc__', 
> '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__']

I got 'cell_contents' as well when I did the 'dir', at least under
Python 2.5.2.



More information about the Python-list mailing list