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.

lambdas, then the global (G) scope, and then the built-in (B) scope—and stops atthe first place the name is found. If the name is not found during this search,<strong>Python</strong> reports an error. As we learned in Chapter 6, names must be assignedbefore they can be used.• When you assign a name in a function (instead of just referring to it in an expression),<strong>Python</strong> always creates or changes the name in the local scope, unless it’sdeclared to be global in that function.• When you assign a name outside a function (i.e., at the top level of a module file,or at the interactive prompt), the local scope is the same as the global scope—the module’s namespace.Figure 16-1 illustrates <strong>Python</strong>’s four scopes. Note that the second E scope lookuplayer—the scopes of enclosing defs orlambdas—can technically correspond to morethan one lookup layer. It only comes into play when you nest functions withinfunctions. *Built-in (<strong>Python</strong>)Names preassigned in the built-in names module: open,range,SyntaxError....Global (module)Names assigned at the top-level of a module file, or declaredglobal in a def within the file.Enclosing function localsNames in the local scope of any and all enclosing functions(def or lambda), from inner to outer.Local (function)Names assigned in any way within a function (defor lambda), and not declared global in that function.Figure 16-1. The LEGB scope lookup rule. When a variable is referenced, <strong>Python</strong> searches for it inthis order: in the local scope, in any enclosing functions’ local scopes, in the global scope, and,finally, in the built-in scope. The first occurrence wins. The place in your code where a variable isassigned usually determines its scope.Also, keep in mind that these rules only apply to simple variable names (such as spam).In Parts V and VI, we’ll see that qualified attribute names (such as object.spam) live inparticular objects and follow a completely different set of lookup rules than the scopeideas covered here. Attribute references (names following periods) search one or moreobjects, not scopes, and may invoke something called “inheritance” (discussed inPart VI).* The scope lookup rule was called the “LGB rule” in the first edition of this book. The enclosing def layer wasadded later in <strong>Python</strong> to obviate the task of passing in enclosing scope names explicitly—a topic usually ofmarginal interest to <strong>Python</strong> beginners that we’ll defer until later in this chapter.Scope Rules | 313

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

Saved successfully!

Ooh no, something went wrong!