Where do nested functions live?
steve at holdenweb.com
Sat Oct 28 10:09:34 CEST 2006
Steven D'Aprano wrote:
> 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
> 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.
> where do nested functions live? How can you access them, for example, to
> read their doc strings?
It doesn't "live" anywhere: if I wrote the function
locvar = 23
would you expect to be able to access foo.locvar?
It's exactly the same thing: the statement
isn't executed until the foo() function is called, and its execution
binds the name bar in foo's local namespace to the function that is defined.
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list