Where do nested functions live?

Frederic Rentsch anthra.norell at vtxmail.ch
Sat Oct 28 18:20:43 CEST 2006


Fredrik Lundh wrote:
> 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>
>
>   
If I may turn the issue around, I could see a need for an inner function 
to be able to access the variables of the outer function, the same way a 
function can access globals. Why? Because inner functions serve to 
de-multiply code segments one would otherwise need to repeat or to 
provide a code segment with a name suggestive of its function. In either 
case the code segment moved to the inner function loses contact with its 
environment, which rather mitigates its benefit.
   If I have an inner function that operates on quite a few outer 
variables it would be both convenient and surely more efficient, if I 
could start the inner function with a declaration analogous to a 
declaration of globals, listing the outer variables which I wish to 
remain writable directly.
   I guess I could put the outer variables into a list as argument to 
the inner function. But while this relieves the inner function of 
returning lots of values it burdens the outer function with handling the 
list which it wouldn't otherwise need.

Frederic





More information about the Python-list mailing list