Scope in 2.2.1

Kragen Sitaker kragen at pobox.com
Mon May 13 19:03:40 EDT 2002


"David LeBlanc" <whisper at oz.net> writes:
> I have grown accustomed by long use to the way that C, C++ and Pascal (and
> asm for that matter!) become aware of declarations. To use an analogy,
> there's a line that moves down the page and things below the line are
> unknown to the compiler since they're not seen yet unless they're forward
> declared.

Yes; unfortunately, this doesn't work in Python because Python doesn't
have declarations, forward, backward, inside, outside, or upside down,
except for the "global" statement.  If Python had declarations, we
could avoid this whole mess.

> Code is parsed based on what's known above the line. Python seems
> to have an implicit per block pre-pass that gets all the bindings before
> statements are parsed. Is this the correct idea?

Python code is parsed sequentially, in a single pass; you will note
that assignment to a global variable is syntactically identical to
assignment to a local variable, and there is no declaration (like C's
typedef and C++'s four other kinds of declarations that do the same
thing) that will change the parsing of code.

However, the bytecode generated by compiling a parsed statement may
indeed depend on statements after it, and yes, this is sometimes
surprising.

> [David quotes somebody he neglects to credit, who signed "Alex" at the bottom]
> > the x in the print may reference either the same binding as given by f's
> > caller, or the binding to 45.  It IS certainly a reference to the *local
> > variable* named x, but what binding of that local variable applies, it's
> > anybody's guess.  "scoping" might be a useful neologism here.
> 
> gaaaaa! this is mad! How can you write a sane program in this sort of
> environment?!?

Goodness, David, I had no idea you were such a functional-programming
enthusiast.  :)




More information about the Python-list mailing list