How to peek inside a decorated function

Terry Reedy tjreedy at udel.edu
Sun Feb 15 03:43:57 EST 2009


Steven D'Aprano wrote:
> 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()?
> 
> If I look at the code object I can see a reference to the original:
> 
>>>> rsay.func_code.co_names
> ('list', 'args', 'reverse', 'func')
> 
> and if I disassemble the code object I can see it being dereferenced:
> 
>>>> dis.dis(rsay.func_code)
> [snip for brevity]
>   5          22 LOAD_DEREF               0 (func)
>              25 LOAD_FAST                0 (args)
>              28 CALL_FUNCTION_VAR        0
>              31 RETURN_VALUE        
> 
> but if I look at the closure object, nothing seems useful:
> 
>>>> dir(rsay.func_closure[0])
> ['__class__', '__cmp__', '__delattr__', '__doc__', 
> '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__']
> 
> 
> and I can't find any other attributes which refers back to the undecorated
> original function.

In 3.0, rsay.__closure__[0].cell_contents would be the original function 
object.




More information about the Python-list mailing list