2 questions about scope

Josiah Carlson jcarlson at uci.edu
Mon Oct 25 14:26:45 EDT 2004


Gabriel Zachmann <zach at cs.uni-bonn.de> wrote:
> 
> I am relatively new to python, but i know some other languages, such as C++,
> fairly well.
> After reading up a little bit in the reference manual, section 4.1,
> and searching this NG, i still have 2 questions about python's scoping
> rules.
> 
> 1. Exactly what are the major differences between python's and C++ scoping
>    rules?

Most of the differences you will never run into.  Here are two that may
effect you in time.

>>> a = 1
>>> def f():
...     b = 2
...     def g():
...         c = 3
...         def h():
...             d = 4
...             print a,b,c,d
...         h()
...     g()
...
>>> f()
1 2 3 4

>>> a = 1
>>> def f():
...     b = 2
...     def g():
...         global a,b
...         a = 2
...         b = 3
...     g()
...     print a, b
...
>>> f()
2 2
>>>
>>> b
3

Generally, you always have read-only access to parent-level scopes, but
if you want write-access to non-global parent scopes, you are out of
luck unless you use object attributes.

>>> class a:
...     pass
...
>>> def f():
...     data = a()
...     data.sub = 1
...     def g():
...         data.sub = 2
...     g()
...     print data.sub
...
>>> f()
2


> 2. Why is it that 'while', 'for', etc., don't introduce a new block?
>    (so that variables bound inside those blocks would be local to those
>    blocks only?)

Last time I checked, C++ didn't introduce new scopes for for and while
loops.  I would imagine Python doesn't introduce new scopes for three
reasons: it is easier not to, not doing so simplifies some algorithms
(name munging can address the "but I wanted that variable" complaints)
and "Flat is better than nested".

 - Josiah




More information about the Python-list mailing list