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.

def test( ):print varlocal(); glob1(); glob2( ); glob3( )print varWhen run, this adds 3 to the global variable (only the first function does not impact it):>>> import thismod>>> thismod.test( )99102>>> thismod.var102This works, and it illustrates the equivalence of globals to module attributes, but it’smuch more work than using the global statement to make your intentions explicit.Scopes and Nested FunctionsSo far, I’ve omitted one part of <strong>Python</strong>’s scope rules (on purpose, because it’s relativelyrarely encountered in practice). However, it’s time to take a deeper look at theletter E in the LEGB lookup rule. The E layer is fairly new (it was added in <strong>Python</strong> 2.2);it takes the form of the local scopes of any and all enclosing function defs. Enclosingscopes are sometimes also called statically nested scopes. Really, the nesting is a lexicalone—nested scopes correspond to physically nested code structures in your program’ssource code.Nested Scope DetailsIn <strong>Python</strong> 3.0, a proposed nonlocal statement is planned that willallow write access to variables in enclosing function scopes, much likethe global statement does today for variables in the enclosing modulescope. This statement will look like the global statement syntactically,but will use the word nonlocal instead. This is still a futurism, so seethe 3.0 release notes for details.With the addition of nested function scopes, variable lookup rules become slightlymore complex. Within a function:• An assignment (X= value) creates or changes the name X in the current localscope, by default. If X is declared global within the function, it creates or changesthe name X in the enclosing module’s scope instead.• A reference (X) looks for the name X first in the current local scope (function);then in the local scopes of any lexically enclosing functions in your source code,from inner to outer; then in the current global scope (the module file); andfinally in the built-in scope (the module _ _builtin_ _). global declarations makethe search begin in the global (module file) scope instead.320 | Chapter 16: Scopes and Arguments

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

Saved successfully!

Ooh no, something went wrong!