Scoping: Is Python and does it matter?

Jeremy Hylton jeremy at beopen.com
Thu Jun 1 00:03:55 EDT 2000


nanotech at pacifier.com (noone) writes:

> What is Python's philosophy? Guido has a whitepaper on Style; has
> he or someone done one on Scoping?
> 
> Here is another example that concerns my coworkers (though I have not had
> this issue, do not see the issue, and would not code this way--what can
> you do?!!):
> 
> Python 1.5.1 (#37, Apr 27 1998, 13:36:17)  [CW CFM68K w/GUSI w/MSL]
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> x=1
> >>> def print_X():
> ...   print x
> ... 
> >>> print_X()
> 1
> >>> def print_X():
> ...   print x
> ...   x=2
> ... 
> >>> print_X()
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 2, in print_X
> NameError: x
> >>> 
> 
> In Perl, the second 'print_X' would succeed because 'x' would be found in
> the outer scope. Python scopes the var to the function due to the
> assignment (it seems). One could use 'global', but then the assignment
> would affect the module var (where in Perl, the assignment might be
> my($x)=2, in which case the "global" x would not be modified).
> 
> Again, I am looking for Python's philosophy (reasoning, excuses,
> whatever! :) so that my coworkers will switch and I will not have to look
> and ugly/bad code because it was fast hacked!
> 

There's a joke that Barry is fond of:  A patient comes in to see a
doctor.  He says, "Doc, it hurts when I move my arm this way."  The
doctor says, "Then don't more your arm that way."

It's hard to give you good advice about the example code you present,
because it's not at all clear what it is supposed to do.  In general,
it is confusing for the same variable name to be re-used for different
purposes within the body of a single function.  It is also confusing
to use the same name for a global and a local when you want to access
both.  Python's rules make it harder for you to write that confusing
code.  Instead, you should come up with different names.

Jeremy



More information about the Python-list mailing list