Re: 2 questions about scope
From: Josiah Carlson (jcarlson_at_uci.edu)
Date: 10/25/04
- Next message: Istvan Albert: "Re: GPL and Python modules."
- Previous message: Ian Bicking: "Re: GPL and Python modules."
- In reply to: Gabriel Zachmann: "2 questions about scope"
- Next in thread: Neal D. Becker: "Re: 2 questions about scope"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 25 Oct 2004 11:26:45 -0700 To: Gabriel Zachmann <zach@cs.uni-bonn.de>, python-list@python.org
Gabriel Zachmann <zach@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
- Next message: Istvan Albert: "Re: GPL and Python modules."
- Previous message: Ian Bicking: "Re: GPL and Python modules."
- In reply to: Gabriel Zachmann: "2 questions about scope"
- Next in thread: Neal D. Becker: "Re: 2 questions about scope"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]