Where do nested functions live?
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).
codetype = type(func.func_code)
for obj in func.func_code.co_consts:
if obj.co_name == name:
raise ValueError("function with name %s not found in %r"
Not exactly something I'd recommend for ordinary usage, but it can be
More information about the Python-list