[Python-Dev] Re: closure semantics
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Thu Oct 23 20:07:06 EDT 2003
> From: John Williams [mailto:jrw at pobox.com]
>
> I can think of two reasonable possibilities--either it refers to the
> innermost possible variable, or the compiler rejects this
> case outright.
> Either way the problem is easy to solve by renaming one of
> the variables.
Going on the principle of least surprise, I have to say that I think explicitly naming the scope in which a variable is to be used is the best approach.
My concern with the other proposal is that introducing code between scopes could silently change the semantics of a piece of code.
I'll use the 'outer' proposal since it's the shortest and least confusing to me ...
def func1()
x = 1
def func2()
def func3()
outer x
x += 2
return func3
return func2()
print func1()
should print:
3
Now, if we change it to:
def func1()
x = 1
def func2()
x = 2
def func3()
outer x
x += 2
return func3
return func2()
print func1()
it would now print:
4
OTOH, specifying the scope prevents this type of error:
def func1()
x = 1
def func2()
def func3()
global x in func1
x += 2
return func3
return func2()
print func1()
and
def func1()
x = 1
def func2()
x = 2
def func3()
global x in func1
x += 2
return func3
return func2()
print func1()
should both print
3
'global x in func1' is also a *lot* easier to explain.
I think these two points should weigh heavily in any decision. I think the need to rename the target scope is of lesser importance.
Tim Delaney
More information about the Python-Dev
mailing list