Text
stringlengths
1
9.41k
That is, to make this sort of code work, we must pass in the current value of the enclosing scope’s variable with a default.
Because defaults are evaluated when the nested function is created (not when it’s later called), each remembers its own value for i: ``` >>> def makeActions(): ... acts = [] ``` `...
for i in range(5):` _# Use defaults instead_ `... acts.append(lambda x, i=i: i ** x)` _# Remember current i_ ``` ...
return acts ... >>> acts = makeActions() ``` `>>> acts[0](2)` _# 0 ** 2_ ``` 0 ``` `>>> acts[2](2)` _# 2 ** 2_ ``` 4 ``` `>>> acts[4](2)` _# 4 ** 2_ ``` 16 ``` This is a fairly obscure case, but it can come up in practice, especially in code that generates callback handler functions for a number of widget...
We’ll talk more about defaults in Chapter 18 and lambdas in Chapter 19, so you may want to return and review this section later.[‡] ###### Arbitrary scope nesting Before ending this discussion, I should note that scopes may nest arbitrarily, but only enclosing function def statements (not classes, described in Part V...
x = 99 ... def f2(): ... def f3(): ``` `... print(x)` _# Found in f1's local scope!_ ``` ...
f3() ``` ‡ In the section “Function Gotchas” on page 518 at the end of this part of the book, we’ll also see that there is an issue with using mutable objects like lists and dictionaries for default arguments (e.g., def f(a=[]))— because defaults are implemented as single objects attached to functions, mutable default...
Depending on whom you ask, this is either considered a feature that supports state retention, or a strange wart on the language. More on this at the end of Chapter 20. **|** ----- ``` ...
f2() ... >>> f1() 99 ``` Python will search the local scopes of all enclosing defs, from inner to outer, after the referencing function’s local scope and before the module’s global scope or built-ins. However, this sort of code is even less likely to pop up in practice.
In Python, we say _flat is better than nested—except in very limited contexts, your life (and the lives of your_ coworkers) will generally be better if you minimize nested function definitions. ###### The nonlocal Statement In the prior section we explored the way that nested functions can reference variables in an e...
It turns out that, as of Python 3.0, we can also change such enclosing scope variables, as long as we declare them in nonlocal statements.
With this statement, nested defs can have both read and write access to names in enclosing functions. The `nonlocal statement is a close cousin to` `global, covered earlier.
Like` `global,` ``` nonlocal declares that a name will be changed in an enclosing scope.
Unlike global, ``` though, nonlocal applies to a name in an enclosing function’s scope, not the global module scope outside all defs.
Also unlike global, nonlocal names must already exist in the enclosing function’s scope when declared—they can exist only in enclosing functions and cannot be created by a first assignment in a nested def. In other words, nonlocal both allows assignment to names in enclosing function scopes and limits scope lookups fo...
The net effect is a more direct and reliable implementation of changeable scope information, for programs that do not desire or need classes with attributes. ###### nonlocal Basics Python 3.0 introduces a new `nonlocal statement, which has meaning only inside a` function: ``` def func(): nonlocal name1, name2, ...
In Python 2.X (including 2.6), when one function def is nested in another, the nested function can reference any of the names defined by assignment in the enclosing def’s scope, but it cannot change them.
In 3.0, declaring the enclosing scopes’ names in a nonlocal statement enables nested functions to assign and thus change such names as well. This provides a way for enclosing functions to provide _writeable state information,_ remembered when the nested function is later called.
Allowing the state to change **|** ----- makes it more useful to the nested function (imagine a counter in the enclosing scope, for instance).
In 2.X, programmers usually achieve similar goals by using classes or other schemes.
Because nested functions have become a more common coding pattern for state retention, though, nonlocal makes it more generally applicable. Besides allowing names in enclosing defs to be changed, the nonlocal statement also forces the issue for references—just like the global statement, nonlocal causes searches for th...
That is, nonlocal also means “skip my local scope entirely.” In fact, the names listed in a nonlocal _must have been previously defined in an enclosing_ ``` def when the nonlocal is reached, or an error is raised.
The net effect is much like global: global means the names reside in the enclosing module, and nonlocal means they reside ``` in an enclosing def.
nonlocal is even more strict, though—scope search is restricted to _only enclosing defs.
That is, nonlocal names can appear only in enclosing defs, not in_ the module’s global scope or built-in scopes outside the defs. The addition of nonlocal does not alter name reference scope rules in general; they still work as before, per the “LEGB” rule described earlier.
The nonlocal statement mostly serves to allow names in enclosing scopes to be changed rather than just referenced. However, global and nonlocal statements do both restrict the lookup rules somewhat, when coded in a function: - global makes scope lookup begin in the enclosing module’s scope and allows names there to b...
Scope lookup continues on to the built-in scope if the name does not exist in the module, but assignments to global names always create or change them in the module’s scope. - nonlocal restricts scope lookup to just enclosing defs, requires that the names already exist there, and allows them to be assigned.
Scope lookup does not continue on to the global or built-in scopes. In Python 2.6, references to enclosing def scope names are allowed, but not assignment. However, you can still use classes with explicit attributes to achieve the same changeable state information effect as nonlocals (and you may be better off doing s...
More on this in a moment; first, let’s turn to some working code to make this more concrete. ###### nonlocal in Action On to some examples, all run in 3.0.
References to enclosing def scopes work as they do in 2.6.
In the following, tester builds and returns the function nested, to be called later, and the state reference in nested maps the local scope of tester using the normal scope lookup rules: **|** ----- ``` C:\\misc>c:\python30\python >>> def tester(start): ``` `...
state = start` _# Referencing nonlocals works normally_ ``` ... def nested(label): ``` `... print(label, state)` _# Remembers state in enclosing scope_ ``` ...
return nested ... >>> F = tester(0) >>> F('spam') spam 0 >>> F('ham') ham 0 ``` Changing a name in an enclosing def’s scope is not allowed by default, though; this is the normal case in 2.6 as well: ``` >>> def tester(start): ...
state = start ... def nested(label): ... print(label, state) ``` `... state += 1` _# Cannot change by default (or in 2.6)_ ``` ...
return nested ... >>> F = tester(0) >>> F('spam') UnboundLocalError: local variable 'state' referenced before assignment ###### Using nonlocal for changes ``` Now, under 3.0, if we declare state in the tester scope as nonlocal within nested, we get to change it inside the nested function, too.
This works even though tester has returned and exited by the time we call the returned nested function through the name ``` F: >>> def tester(start): ``` `...
state = start` _# Each call gets its own state_ ``` ... def nested(label): ``` `... nonlocal state` _# Remembers state in enclosing scope_ ``` ... print(label, state) ``` `...
state += 1` _# Allowed to change it if nonlocal_ ``` ...
return nested ... >>> F = tester(0) ``` `>>> F('spam')` _# Increments state on each call_ ``` spam 0 >>> F('ham') ham 1 >>> F('eggs') eggs 2 ``` As usual with enclosing scope references, we can call the tester factory function multiple times to get multiple copies of its state in memory.
The state object in the enclosing scope is essentially attached to the nested function object returned; each call makes a **|** ----- new, distinct state object, such that updating one function’s state won’t impact the other.
The following continues the prior listing’s interaction: `>>> G = tester(42)` _# Make a new tester that starts at 42_ ``` >>> G('spam') spam 42 ``` `>>> G('eggs')` _# My state information updated to 43_ ``` eggs 43 ``` `>>> F('bacon')` _# But F's is where it left off: at 3_ ``` bacon 3 # Each ca...
First, unlike the global statement, nonlocal names really must have previously been assigned in an enclosing def’s scope when a ``` nonlocal is evaluated, or else you’ll get an error—you cannot create them dynamically ``` by assigning them anew in the enclosing scope: ``` >>> def tester(start): ...
def nested(label): ``` `... nonlocal state` _# Nonlocals must already exist in enclosing def!_ ``` ... state = 0 ... print(label, state) ...
return nested ... SyntaxError: no binding for nonlocal 'state' found >>> def tester(start): ... def nested(label): ``` `... global state` _# Globals don't have to exist yet when declared_ `...
state = 0` _# This creates the name in the module now_ ``` ... print(label, state) ...
return nested ... >>> F = tester(0) >>> F('abc') abc 0 >>> state 0 ``` Second, nonlocal restricts the scope lookup to just enclosing defs; nonlocals are not looked up in the enclosing module’s global scope or the built-in scope outside all ``` defs, even if they are already there: >>> spam = 99 >>> def...
def nested(): ``` `... nonlocal spam` _# Must be in a def, not the module!_ ``` ... print('Current=', spam) ... spam += 1 ...
return nested ... SyntaxError: no binding for nonlocal 'spam' found ``` **|** ----- These restrictions make sense once you realize that Python would not otherwise generally know which enclosing scope to create a brand new name in.
In the prior listing, should spam be assigned in tester, or the module outside?
Because this is ambiguous, Python must resolve nonlocals at function creation time, not function call time. ###### Why nonlocal? Given the extra complexity of nested functions, you might wonder what the fuss is about.
Although it’s difficult to see in our small examples, state information becomes crucial in many programs.
There are a variety of ways to “remember” information across function and method calls in Python.
While there are tradeoffs for all, ``` nonlocal does improve this story for enclosing scope references—the nonlocal state ``` ment allows multiple copies of changeable state to be retained in memory and addresses simple state-retention needs where classes may not be warranted. As we saw in the prior section, the follo...
Each call to tester creates a little self-contained package _of changeable information, whose names do not clash with any other part of the_ program: ``` def tester(start): state = start # Each call gets its own state def nested(label): nonlocal state # Remembers state in enclosing sco...
If you are using Python 2.6, other options are available, depending on your goals.
The next two sections present some alternatives. ###### Shared state with globals One usual prescription for achieving the nonlocal effect in 2.6 and earlier is to simply move the state out to the global scope (the enclosing module): ``` >>> def tester(start): ``` `...
global state` _# Move it out to the module to change it_ `... state = start` _# global allows changes in module scope_ ``` ... def nested(label): ... global state ... print(label, state) ...
state += 1 ...
return nested ... >>> F = tester(0) ``` `>>> F('spam')` _# Each call increments shared global state_ **|** ----- ``` spam 0 >>> F('eggs') eggs 1 ``` This works in this case, but it requires `global declarations in both functions and is` prone to name collisions in the global scope (what if “state” is al...
A worse, and more subtle, problem is that it only allows for a single shared copy of the state information in the module scope—if we call tester again, we’ll wind up resetting the module’s state variable, such that prior calls will see their state overwritten: `>>> G = tester(42)` _# Resets state's single copy in glob...
As an added benefit, each instance of a class gets a fresh copy of the state information, as a natural byproduct of Python’s object model. We haven’t explored classes in detail yet, but as a brief preview, here is a reformulation of the tester/nested functions used earlier as a class—state is recorded in objects expli...
To make sense of this code, you need to know that a def within a `class like this works exactly like a` `def outside of a` `class, except that the` function’s self argument automatically receives the implied subject of the call (an instance object created by calling the class itself): `>>> class tester:` _# Class-base...
def __init__(self, start):` _# On object construction,_ `... self.state = start` _# save state explicitly in new object_ ``` ... def nested(self, label): ``` `...
print(label, self.state)` _# Reference state explicitly_ `...
self.state += 1` _# Changes are always allowed_ ``` ... ``` `>>> F = tester(0)` _# Create instance, invoke __init___ `>>> F.nested('spam')` _# F is passed to self_ ``` spam 0 >>> F.nested('ham') ham 1 ``` `>>> G = tester(42)` _# Each instance gets new copy of state_ `>>> G.nested('toast')` _# Changing one doe...
__call__ intercepts direct calls on an instance, so we don’t need to call a named method: ``` >>> class tester: ... def __init__(self, start): ... self.state = start ``` `...
def __call__(self, label):` _# Intercept direct instance calls_ `... print(label, self.state)` _# So .nested() not required_ ``` ...
self.state += 1 ... >>> H = tester(99) ``` `>>> H('juice')` _# Invokes __call___ ``` juice 99 >>> H('pancakes') pancakes 100 ``` Don’t sweat the details in this code too much at this point in the book; we’ll explore classes in depth in Part VI and will look at specific operator overloading tools like ``` __...
Such trivial state cases are more common than you might think; in such contexts, nested defs are sometimes more lightweight than coding classes, especially if you’re not familiar with OOP yet.
Moreover, there are some scenarios in which nested defs may actually work better than classes (see the description of method decorators in Chapter 38 for an example that is far beyond this chapter’s scope). ###### State with function attributes As a final state-retention option, we can also sometimes achieve the same...
Although this scheme may not be as intuitive to some, it also allows the state variable to be accessed _outside the nested_ function (with nonlocals, we can only see state variables within the nested def): ``` >>> def tester(start): ...
def nested(label): ``` `... print(label, nested.state)` _# nested is in enclosing scope_ `... nested.state += 1` _# Change attr, not nested itself_ **|** ----- `...
nested.state = start` _# Initial state after func defined_ ``` ...
return nested ... >>> F = tester(0) ``` `>>> F('spam')` _# F is a 'nested' with state attached_ ``` spam 0 >>> F('ham') ham 1 ``` `>>> F.state` _# Can access state outside functions too_ ``` 2 >>> ``` `>>> G = tester(42)` _# G has own state, doesn't overwrite F's_ ``` >>> G('eggs') eggs 42 >>> F(...
This ``` code also relies on the fact that changing an object in-place is not an assignment to a name; when it increments nested.state, it is changing part of the object nested references, not the name `nested itself.
Because we’re not really assigning a name in the` enclosing scope, no nonlocal is needed. As you can see, globals, nonlocals, classes, and function attributes all offer state-retention options.
Globals only support shared data, classes require a basic knowledge of OOP, and both classes and function attributes allow state to be accessed outside the nested function itself.
As usual, the best tool for your program depends upon your program’s goals. ###### Chapter Summary In this chapter, we studied one of two key concepts related to functions: scopes (how variables are looked up when they are used).
As we learned, variables are considered local to the function definitions in which they are assigned, unless they are specifically declared to be global or nonlocal.
We also studied some more advanced scope concepts here, including nested function scopes and function attributes.
Finally, we looked at some general design ideas, such as the need to avoid globals and cross-file changes. In the next chapter, we’re going to continue our function tour with the second key function-related concept: argument passing.
As we’ll find, arguments are passed into a function by assignment, but Python also provides tools that allow functions to be flexible in how items are passed.
Before we move on, let’s take this chapter’s quiz to review the scope concepts we’ve covered here. **|** ----- ###### Test Your Knowledge: Quiz 1.
What is the output of the following code, and why? ``` >>> X = 'Spam' >>> def func(): ... print(X) ... >>> func() ``` 2.
What is the output of this code, and why? ``` >>> X = 'Spam' >>> def func(): ... X = 'NI!' ... >>> func() >>> print(X) ``` 3.
What does this code print, and why? ``` >>> X = 'Spam' >>> def func(): ... X = 'NI' ... print(X) ... >>> func() >>> print(X) ``` 4.
What output does this code produce? Why? ``` >>> X = 'Spam' >>> def func(): ... global X ... X = 'NI' ... >>> func() >>> print(X) ``` 5.
What about this code—what’s the output, and why? ``` >>> X = 'Spam' >>> def func(): ... X = 'NI' ... def nested(): ... print(X) ...
nested() ... >>> func() >>> X ``` **|** ----- 6. How about this example: what is its output in Python 3.0, and why? ``` >>> def func(): ... X = 'NI' ...
def nested(): ... nonlocal X ... X = 'Spam' ... nested() ... print(X) ... >>> func() ``` 7.
Name three or more ways to retain state information in a Python function. ###### Test Your Knowledge: Answers 1.
The output here is 'Spam', because the function references a global variable in the enclosing module (because it is not assigned in the function, it is considered global). 2.
The output here is 'Spam' again because assigning the variable inside the function makes it a local and effectively hides the global of the same name.
The print statement finds the variable unchanged in the global (module) scope. 3.
It prints 'NI' on one line and 'Spam' on another, because the reference to the variable within the function finds the assigned local and the reference in the print statement finds the global. 4.
This time it just prints 'NI' because the global declaration forces the variable assigned inside the function to refer to the variable in the enclosing global scope. 5.
The output in this case is again 'NI' on one line and 'Spam' on another, because the print statement in the nested function finds the name in the enclosing function’s local scope, and the print at the end finds the variable in the global scope. 6.
This example prints 'Spam', because the nonlocal statement (available in Python 3.0 but not 2.6) means that the assignment to X inside the nested function changes ``` X in the enclosing function’s local scope.
Without this statement, this assignment ``` would classify X as local to the nested function, making it a different variable; the code would then print 'NI' instead. 7.
Although the values of local variables go away when a function returns, you can make a Python function retain state information by using shared global variables, enclosing function scope references within nested functions, or using default argument values.