Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing inner function of a function

def myFunc( a, b ):
  def innerFunc( c ):
    print c
  innerFunc( 2 )
  print a, b

How can I access the inner function directly? I want the object/address of that function in the format

<function innerFunc at 0xa0d5fb4>

I tried with myFunc._getattr_( 'innerFunc' ) but that didn't work.

like image 932
crk Avatar asked Dec 12 '22 01:12

crk


1 Answers

As the function does not exists until the function call (and only exists during it), you cannot access it.

If the closure is not important, you can build the inner function directly from the code constant placed inside the outer function:

inner = types.FunctionType(myFunc.__code__.co_consts[1], globals())

The position inside the const values of the function may vary...

This solution does not require calling myFunc.

like image 54
JBernardo Avatar answered Dec 22 '22 08:12

JBernardo