Variable scoping rules in Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 8 13:09:14 EDT 2007


On Mon, 08 Oct 2007 07:17:36 -0700, joshua.davies wrote:

> I went back and re-read chapter 13 of "Learning Python", which talks
> about variable scoping rules, and I can't figure out why Python is
> saying this variable in Unbound.  It works if I insert:
> 
>   global COLUMNS
> 
> before the "if" statement... but I don't understand why.  Is the
> interpreter scanning my entire function definition before executing it,
> recognizing that I *might* assign COLUMNS to a value, and deciding that
> it's a local on that basis?

Almost right, but not quite.

You are right that Python decides that COLUMNS is local, but you're wrong 
about when that decision gets made. Python does not re-scan your function 
every time you execute it, but only once, when it is compiled.

Compiling the function might take one pass of the source code, or two, or 
a thousand for all we know; that's an irrelevant detail of interest only 
to compiler designers and the chronically curious. What's important is 
that once the function is compiled, the decision is already made about 
whether COLUMNS is local or not, and the virtual machine that executes 
your function only needs to interpret the byte-code in a single pass.



-- 
Steven.



More information about the Python-list mailing list