How to peek inside a decorated function

Steven D'Aprano steve at
Sun Feb 15 01:29:42 EST 2009

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)
        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.


More information about the Python-list mailing list