2
def foo():
    print "I am foo"
    def bar1():
       print "I am bar1"
    def bar2():
       print "I am bar2"
    def barN():
       print "I am barN"


funobjs_in_foo = get_nest_functions(foo)

def get_nest_functions(funobj):
    #how to write this function??

How to get all the nested function objects? I can get the code object of the nesting functions through funobj.func_code.co_consts. But I haven't found a way to get the function objects for the nested functions.

Any help is appreciated.

2
  • check this : stackoverflow.com/questions/1095543/…
    – Moj
    Apr 26, 2013 at 8:49
  • Thanks. The inspect frame only hold the code objects. Somebody proposed a way to get function object from code object by using gc. But it doesn't work for this nested function scenario.
    – limi
    Apr 26, 2013 at 8:53

1 Answer 1

6

As you noticed, foo.func_code.co_consts only contains the code objects, not function objects.

You can't get the function objects simply because they don't exist. They are recreated whenever the function is called (and only the code objects are re-used).

Confirm that using:

>>> def foo():
...     def bar():
...         print 'i am bar'
...     return bar
....
>>> b1 = foo()
>>> b2 = foo()
>>> b1 is b2
False
>>> b1.func_code is b2.func_code
True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.