namespaces & indentation
Tim Peters
tim.one at home.com
Fri Dec 22 21:30:22 EST 2000
[unattributed]
> I always thought that I understood Python's scoping, but then I
> came across that code:
> > def t(x):
> > if x == 1:
> > c = 'yeah'
> > return c
[Chris Schaller]
> If I execute t(1), I'll get 'yeah', but otherwise there'll be an
> error message. According to the indentation level c is only valid
> within the if-clause, but not on the outside.
You made that up out of your own head, you know <wink>.
> So I guess, the indentation level only defines the lines of code
> that belong to the if-clause, but has nothing to do with scopes.
Very close. Scopes are defined with respect to "execution frames", which
are in turn attached to "code blocks", and the code block of a function is
its entire body (less the bodies of nested functions and classes). The
complete rules are here:
http://www.python.org/doc/current/ref/execframes.html
Well worth reading! The answers to many "deep" questions are waiting there.
> That's very confusing, I've already programmed a lot in Python,
> but only due to a program error (I forgot to initialize c at the
> beginning of the function - a common error) and an unsuccessful
> test this happened to a program after months of error-free running.
>
> Any comments?
1. Strive to test all paths thru each function (good advice regardless of
language).
2. It's likely that a framework for warning messages will be added to Python
2.1. In the case above, the compiler could do some flow analysis and
generate a compile-time warning that "c" may not be bound at the time the
"return" is executed. Java's rules make that kind of code a compile-time
error, but some people play such extreme tricks with Python's dynamicism
that we'll probably have to settle for a nag msg in Python.
if-thine-eye-offends-thee-pluck-it-out-ly y'rs - tim
More information about the Python-list
mailing list