Accessing nested functions for testing

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue May 20 17:38:41 EDT 2003


On Tue, 2003-05-20 at 00:13, Terry Reedy wrote:

> Yes and no, depending on what you mean by access.  The def bar
> statement is *not* executed when you execute the def foo statement but
> only when you call foo() sometime after, so until then, there is no
> bar to access.

Ah, of course!  That makes it all much clearer.  Thanks also to Gerrit
Hall, Paul Foley, Erik Max Francis, and monsterkodi for responding.

It is possible to execute a nested function by finding the nested code
object in the co_consts member of the outer function, and evaluating the
object directly.  However, I presume if one is making use of nested
namespaces, this may have unintended behavior (the inner namespace it
relies on won't be around.  Is this correct?).

So, while an interesting curiosity, and possibly useful for some things,
it isn't something I'll be relying on for testing my nested functions.
:)



$ python
Python 2.2.2 (#1, Mar 21 2003, 23:01:54)
>>> def foo():
...     def bar():
...         print 2
...     print 1
...     bar()
...

>>> foo()
1
2

>>> foo.func_code
<code object foo at 0x8164d10, file "<stdin>", line 1>

>>> foo.func_code.co_consts
(None, <code object bar at 0x81648b0, file "<stdin>", line 2>, 1)

>>> foo.func_code.co_consts[1]
<code object bar at 0x81648b0, file "<stdin>", line 2>

>>> # Evaluate the inner "bar" function
>>> eval(foo.func_code.co_consts[1])
2



Cheers.

-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list