Where do nested functions live?

Fredrik Lundh fredrik at pythonware.com
Sat Oct 28 03:59:29 EDT 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
> 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.
> 
> where do nested functions live?

in the local variable of an executing function, just like the variable 
"bar" in the following function:

     def foo():
         bar = "who am I? where do I live?"

(yes, an inner function is *created* every time you execute the outer 
function.  but it's created from prefabricated parts, so that's not a 
very expensive process).

</F>




More information about the Python-list mailing list