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.

vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124
limi
  • 832
  • 7
  • 19
  • check this : http://stackoverflow.com/questions/1095543/get-name-of-calling-functions-module-in-python – Moj Apr 26 '13 at 08: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 '13 at 08:53

1 Answers1

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
Kos
  • 70,399
  • 25
  • 169
  • 233