Scoping: Is Python and does it matter?

Russell Wallace rwallace at
Sat May 27 23:13:00 EDT 2000

noone wrote:
> 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!

Well, I'm a Python newbie and no expert on the philosophy, but this one
strikes me as very straightforward.  Here's what I'd say:

Is x a local variable or a global?  If it's global, you've got to
declare it as one.  Yeah that's a nuisance, but it's not too big a one
to live with; you don't have to declare locals, and they're more common
than globals.

If it's a local, then you've got to assign it before you use it.  What's
problematic about that?  If you don't want to assign it a meaningful
value, just stick x = 0 at the top of the function.

"To summarize the summary of the summary: people are a problem."
Russell Wallace
mailto:rwallace at

More information about the Python-list mailing list