Where do nested functions live?

Carl Banks pavlovevidence at gmail.com
Wed Nov 1 12:30:50 CET 2006


Ben Finney wrote:
> "Steven D'Aprano" <steve at REMOVE.THIS.cybersource.com.au> writes:
>
> > I defined a nested function:
> >
> > def foo():
> >     def bar():
> >         return "bar"
> >     return "foo " + bar()
> >
> > which works. Knowing how Python loves namespaces, I thought I could
> > do this:
> >
> > >>> foo.bar()
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > AttributeError: 'function' object has no attribute 'bar'
> >
> > but it doesn't work as I expected.
>
> Functions don't get attributes automatically added to them the way
> class do. The main exception is the '__doc__' attribute, referring to
> the doc string value.
>
> > where do nested functions live?
>
> They live inside the scope of the function. Inaccessible from outside,

Not so fast. You can get at the nested function by peeking inside code
objects (all bets off for Pythons other than CPython).

import new
def extract_nested_function(func,name):
    codetype = type(func.func_code)
    for obj in func.func_code.co_consts:
        if isinstance(obj,codetype):
            if obj.co_name == name:
                return new.function(obj,func.func_globals)
    raise ValueError("function with name %s not found in %r"
        % (name,func))


Not exactly something I'd recommend for ordinary usage, but it can be
done.


Carl Banks




More information about the Python-list mailing list