Reasoning behind nested scope

Peter Otten __peter__ at web.de
Tue Aug 3 16:39:03 CEST 2004


Andy Baker wrote:

> (On a side note is there any way to call a nested function from outside
> the parent? I was kind of expecting nested functions to be addressable
> through dot notation like methods are but I can see why that wouldn't be
> quite right. This might be a better question for the tutor list...)

When you are nesting functions, you don't get one function sitting inside
another function. Instead, the function creation code of the "inner"
function is executed every time to the effect that you get a new inner
function every time you call the outer one:

>>> def make():
...     def f(): return "shoobidoo"
...     return f
...
>>> f1 = make()
>>> f2 = make()
>>> f1(), f2()
('shoobidoo', 'shoobidoo')
>>> f1 is f2
False

You wouldn't do that in cases like the above, when you get nothing in return
for the extra overhead, but somtimes nesting is useful - because of the
change in the scoping rules you now get readonly-closures:

>>> def make(s):
...     def f(): return s
...     return f
...
>>> f1 = make("now")
>>> f2 = make("what")
>>> f1(), f2()
('now', 'what')

Peter




More information about the Python-list mailing list