Scoping: Is Python and does it matter?

noone nanotech at pacifier.com
Sat May 27 20:42:27 EDT 2000


gmcm at hypernet.com (Gordon McMillan) writes:

>Quentin Crain <nanotech at europa.com> wrote:

>>In Perl one may do something like:
>>
>>$success=1;
>>foreach ... {
>>  my($success);         # $success is "local" to this loop
>>  . . .
>>}
>>print $success;         # $success holds whatever value it did before

>>In Python, loops have no scope. Correct?

>Right - Python does not have a separate scope for code inside a 
>loop.

>>Does this matter? What do the "experts" do in cases like this?

>In this particular case, there's a nice idiom that makes a flag variable 
>unnecessary:

>for ...:
>  if <test for failure>:
>    break
>else:
>  # never hit the break
>  print "succeeded!"

I am attempting to get the word out about Python in my company. We use a
lot of Perl. Whitespace is NOT a concern but scoping seems to be.

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!

Thanks!!

Quentin ('Q')

>- Gordon

Thanks again Gordon for your time!
-- 
-------------------------------------------------------------------------
I think we are miscommunicating. I actually expected some confusion with
my last response and I am not sure if there actually was some, but I feel
like it. So, my message is going to assume I did not make my points, but



More information about the Python-list mailing list