12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Local Names Are Detected StaticallyAs you know, <strong>Python</strong> classifies names assigned in a function as locals by default;they live in the function’s scope and exist only while the function is running. What Ididn’t tell you is that <strong>Python</strong> detects locals statically, when it compiles the def’scode, rather than by noticing assignments as they happen at runtime. This leads toone of the most common oddities posted on the <strong>Python</strong> newsgroup by beginners.Normally, a name that isn’t assigned in a function is looked up in the enclosing module:>>> X = 99>>> def selector( ): # X used but not assigned... print X # X found in global scope...>>> selector( )99Here, the X in the function resolves to the X in the module. But watch what happensif you add an assignment to X after the reference:>>> def selector( ):... print X # Does not yet exist!... X = 88 # X classified as a local name (everywhere)... # Can also happen if "import X", "def X"...>>> selector( )Traceback (most recent call last):File "", line 1, in ?File "", line 2, in selectorUnboundLocalError: local variable 'X' referenced before assignmentYou get an undefined name error, but the reason is subtle. <strong>Python</strong> reads andcompiles this code when it’s typed interactively or imported from a module. Whilecompiling, <strong>Python</strong> sees the assignment to X, and decides that X will be a local nameeverywhere in the function. But, when the function is actually run, because theassignment hasn’t yet happened when the print executes, <strong>Python</strong> says you’re usingan undefined name. According to its name rules, it should say this; the local X is usedbefore being assigned. In fact, any assignment in a function body makes a namelocal. Imports, =, nested defs, nested classes, and so on, are all susceptible to thisbehavior.The problem occurs because assigned names are treated as locals everywhere in afunction, not just after the statements where they are assigned. Really, the previousexample is ambiguous at best: was the intention to print the global X and then createa local X, or is this a genuine programming error? Because <strong>Python</strong> treats X as a localeverywhere, it is an error; if you really mean to print the global X, you need to declareit in a global statement:>>> def selector( ):... global X # Force X to be global (everywhere)... print X... X = 88372 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!