Accessing nested functions for testing

Terry Reedy tjreedy at udel.edu
Tue May 20 03:13:12 EDT 2003


"Chad Netzer" <cnetzer at mail.arc.nasa.gov> wrote in message
news:mailman.1053402089.19012.python-list at python.org...
> Is there any way to access a nested function as though it were not
> nested (ie. for testing it directly)?
>
> For example:
>
> def foo():
>     def bar():
>         pass
>     bar()

> Is it possible to execute bar from outside of foo?  I can't even
find a
> way to see or access bar at all, from the global scope.
>
> My intuition says this is not possible, I'm just curious if that is
> truly the case.

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.  Similar, the binding of 'bar' disappears when foo()
finishes.  So, to keep the function object alive and accessible, you
must pass it out of the function by assigning to a global, a slot in a
mutable arg, or by returning it.  Returning an inner function whose
construction depends on outer function args is a standard idiom.  You
then access like any other function.

def foo(msg1):
    def bar(msg2):
        print msg1, msg2
    return bar

hmm = foo('haha')
hmm('gotcha')

# prints
haha gotcha

Terry J. Reedy






More information about the Python-list mailing list