Nested scopes: why is it weird?

Cliff Wells logiplexsoftware at earthlink.net
Fri Sep 7 21:59:12 CEST 2001


On Friday 07 September 2001 12:27, Paul Prescod wrote:

> Why forevermore? PEP a change to the behaviour and then we can put in a
> warning. Python's current behaviour is both confusing and dangerous and
> I would love to see someone champion a change. This just shouldn't
> silently do the wrong thing:
>
> a = 5
>
> def foo():
>    a = 6
>
> It would be better to require one of the names to be changed.

It silently does the right thing.  Changing the value of a variable from an 
enclosing scope is a _bad_ idea.  This is what is called a "side effect" and 
was one of the things structured programming was created to prevent.  This is 
bad:

>>> a = 5
>>> foo() 
>>> a
6

If a function is going to alter a global variable or a variable from an 
enclosing scope, then it should be passed as an argument or returned as a 
value so that someone reading the code can reasonably expect that variable to 
be changed.  Better:

>>> a = 5
>>> a = foo()
>>> a
6

Note that _accessing_ a variable from an enclosing scope (or global, for that 
matter), isn't nearly as bad and again, Python does the correct thing: it 
allows you to see the variables from the enclosing scope, but the minute you 
try to assign to them, they become local to the current scope (even if you do 
the assignment _after_ you try to read the value - this IS confusing if you 
don't know why)

Regards,

-- 
Cliff Wells
Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308
(800) 735-0555 x308




More information about the Python-list mailing list