[Python-Dev] Visibility scope for "for/while/if" statements
Nick Coghlan
ncoghlan at gmail.com
Sat Sep 24 04:22:23 CEST 2005
Andrew Koenig wrote:
>>Interestingly enough, not all C++ compilers (Microsoft) hid variables
>>created in for loops
>>(http://www.devx.com/cplus/10MinuteSolution/28908/0/page/2).
>
>
> That's because the C++ spec changed during standardization, when the
> standards committee realized the original idea was a mistake.
>
> One of the convincing cases:
>
> if (x)
> for (int i = 0; i != 10; ++i) { }
>
> Is I in scope after the if statement? If so, what value does it have if x
> is false? If not, then apparently the subject of an "if" statement is a
> scope...so why can't I write this?
>
> if (x)
> int i = 42;
>
> and have i go out of scope?
The difference is that C++ uses {} to delineate a new scope, whereas Python
uses only def statements.
The behaviour in C++ and C99 can indeed be quite handy, and aligns perfectly
with the static type system of those languages. Importantly, creating a new
scope is cheap - it's just a matter of moving the stack pointer around a bit
(and maybe invoking some destructors that would have been invoked eventually
anyway).
Python, however, uses a dynamic name binding system and scopes are expensive
because they require setting up all of the machinery to support nested
visibility. That is, additional inline scoping would add significant *runtime*
overhead. So a different design choice was made in Python, but that choice is
still internally consistent.
Using the above example:
if x:
for i in range(10): pass
print i
if x:
i = 42
print i
What happens on the 'print i' line in Python if 'x' is false? Easy: attempting
to access 'i' will result in "UnboundLocalError" being raised at runtime, just
as it would if the 'print i' line was *before* the if statement. That's
because the name 'i' *is* in scope - it just hasn't been bound to anything yet.
As Guido has said, this is really a discussion for c.l.p. Even before taking
it there, however, I suggest reviewing the c.l.p discussion from January
regarding the idea of 'statement local namespaces' [1] (and also checking the
archives to see if the discussion has moved on since then, as I haven't been
following c.l.p. for a good long while).
Regards,
Nick.
[1] http://mail.python.org/pipermail/python-list/2005-January/259556.html
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.blogspot.com
More information about the Python-Dev
mailing list