Access to function internal function

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

How can I access the internal function directly? I want the object / address of this function in the format

 <function innerFunc at 0xa0d5fb4> 

I tried with myFunc._getattr_ ('innerFunc') , but that did not work.

+4
source share
4 answers

what you can do is either return the function or attach it to its parent object when called ...

 >>> def myFunc( a, b ): ... def innerFunc( c ): ... print c ... innerFunc( 2 ) ... myFunc.innerFunc = innerFunc ... print a, b ... >>> >>> myFunc(1,2) 2 1 2 >>> myFunc.innerFunc(3) 3 >>> 

although, apparently, you can access the source code using a special attribute that has function objects ... myFunc.func_code , although it seems that this is access to some serious materials

 >>> help(myFunc.func_code) Help on code object: class code(object) | code(argcount, nlocals, stacksize, flags, codestring, constants, names, | varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) | | Create a code object. Not for the faint of heart. | 


+4
source

Since the function does not exist before the function is called (and exists only during it), you cannot access it.

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

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

The position inside the constant values โ€‹โ€‹of the function can change ...

This solution does not require calling myFunc .

+5
source

You can not. The inner function does not exist until the outer function is called, and will be reduced when the outer function exits, which in this case means that it ceases to exist.

+2
source

You cannot call innerFunc directly from outside myFunc because it is inside the myFunc namespace. One way to call innerFunc is to return an innerFunc object from myFunc

like this:

 def myFunc( a, b ): def innerFunc( c ): print c print a, b return innerFunc #return the innerFunc from here x=myFunc(1,2) x(3) # calling x now calls innerFunc 
+2
source

All Articles