Text stringlengths 1 9.41k |
|---|
Suppose we wrote the
following code in a module file:
```
# Global scope
X = 99 # X and func assigned in module: global
def func(Y): # Y and Z assigned in function: locals
# Local scope
Z = X + Y # X is a global
return Z
func(1) # func in module: result=100
```
This module and... |
func is global for the same
reason; the def statement assigns a function object to the name func at the top level
of the module.
**|**
-----
_Local names: Y, Z_
```
Y and Z are local to the function (and exist only while the function runs) because
```
they are both assigned values in the function definition: Z b... |
For instance, in the
preceding example, the argument Y and the addition result Z exist only inside the function; these names don’t interfere with the enclosing module’s namespace (or any other
function, for that matter).
The local/global distinction also makes functions easier to understand, as most of the
names a fun... |
Also, because you can be sure that local names will not be changed by some
remote function in your program, they tend to make programs easier to debug and
modify.
###### The Built-in Scope
We’ve been talking about the built-in scope in the abstract, but it’s a bit simpler than
you may think. |
Really, the built-in scope is just a built-in module called builtins, but
you have to import builtins to query built-ins because the name builtins is not itself
built-in....
No, I’m serious! |
The built-in scope is implemented as a standard library module named
```
builtins, but that name itself is not placed in the built-in scope, so you have to import
```
it in order to inspect it. |
Once you do, you can run a dir call to see which names are
predefined. |
In Python 3.0:
```
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis',
...many more names omitted...
'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 's... |
Also in this list are the
special names None, True, and False, though they are treated as reserved words. |
Because
Python automatically searches this module last in its LEGB lookup, you get all the
names in this list “for free;” that is, you can use them without importing any modules.
Thus, there are really two ways to refer to a built-in function—by taking advantage of
the LEGB rule, or by manually importing the builtins m... |
The careful
reader might also notice that because the LEGB lookup procedure takes the first occurrence of a name that it finds, names in the local scope may override variables of the
same name in both the global and built-in scopes, and global names may override builtins. |
A function can, for instance, create a local variable called open by assigning to it:
```
def hider():
open = 'spam' # Local variable, hides built-in
...
open('data.txt') # This won't open a file now in this scope!
```
However, this will hide the built-in function called open that lives in the... |
It’s also usually a bug, and a nasty one at that, because Python will not issue a
warning message about it (there are times in advanced programming where you may
really want to replace a built-in name by redefining it in your code).
Functions can similarly hide global variables of the same name with locals:
```
X = ... |
Because of this, there is
no way to change a name outside a function without adding a global (or nonlocal)
declaration to the def, as described in the next section.
_Version skew note: Actually, the tongue twisting gets a bit worse. |
The_
Python 3.0 builtins module used here is named __builtin__ in Python
2.6. |
And just for fun, the name __builtins__ (with the “s”) is preset in
most global scopes, including the interactive session, to reference the
module known as builtins (a.k.a. |
__builtin__ in 2.6).
That is, after importing builtins, __builtins__ is builtins is True in
3.0, and __builtins__ is __builtin__ is True in 2.6. |
The net effect is
that we can inspect the built-in scope by simply running
```
dir(__builtins__) with no import in both 3.0 and 2.6, but we are ad
```
vised to use builtins for real work in 3.0. |
Who said documenting this
stuff was easy?
**|**
-----
###### The global Statement
The global statement and its nonlocal cousin are the only things that are remotely like
declaration statements in Python. |
They are not type or size declarations, though; they
are namespace declarations. |
The global statement tells Python that a function plans to
change one or more global names—i.e., names that live in the enclosing module’s scope
(namespace).
We’ve talked about global in passing already. |
Here’s a summary:
- Global names are variables assigned at the top level of the enclosing module file.
- Global names must be declared only if they are assigned within a function.
- Global names may be referenced within a function without being declared.
In other words, global allows us to change names that live... |
As we’ll see later, the nonlocal statement is almost identical but applies
to names in the enclosing def’s local scope, rather than names in the enclosing module.
The global statement consists of the keyword global, followed by one or more names
separated by commas. |
All the listed names will be mapped to the enclosing module’s
scope when assigned or referenced within the function body. |
For instance:
```
X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def
```
**|**
-----
```
func()
print(X) # Prints 99
```
We’ve added a global declaration to the example here, such that the X inside the def
now refers to the X outside the def; they... |
Here is a slightly
more involved example of global at work:
```
y, z = 1, 2 # Global variables in module
def all_global():
global x # Declare globals assigned
x = y + z # No need to declare y, z: LEGB rule
```
Here, x, y, and z are all globals inside the function all_global. |
y and z are global because
they aren’t assigned in the function; x is global because it was listed in a global statement
to map it to the module’s scope explicitly. |
Without the global here, x would be considered local by virtue of the assignment.
Notice that y and z are not declared global; Python’s LEGB lookup rule finds them in
the module automatically. |
Also, notice that x might not exist in the enclosing module
before the function runs; in this case, the assignment in the function creates x in the
module.
###### Minimize Global Variables
By default, names assigned in functions are locals, so if you want to change names
outside functions you have to write extra code... |
This is by`
design—as is common in Python, you have to say more to do the potentially “wrong”
thing. |
Although there are times when globals are useful, variables assigned in a def are
local by default because that is normally the best policy. |
Changing globals can lead to
well-known software engineering problems: because the variables’ values are
dependent on the order of calls to arbitrarily distant functions, programs can become
difficult to debug.
Consider this module file, for example:
```
X = 99
def func1():
global X
X = 88
def func2():
... |
What will the value
of X be here? |
Really, that question has no meaning unless it’s qualified with a point of
reference in time—the value of X is timing-dependent, as it depends on which function
was called last (something we can’t tell from this file alone).
**|**
-----
The net effect is that to understand this code, you have to trace the flow of c... |
And, if you need to reuse or modify the code, you have to
keep the entire program in your head all at once. In this case, you can’t really use one
of these functions without bringing along the other. |
They are dependent on (that is,
_coupled with) the global variable. |
This is the problem with globals—they generally_
make code more difficult to understand and use than code consisting of self-contained
functions that rely on locals.
On the other hand, short of using object-oriented programming and classes, global
variables are probably the most straightforward way to retain shared st... |
Other
techniques, such as default mutable arguments and enclosing function scopes, can
achieve this, too, but they are more complex than pushing values out to the global scope
for retention.
Some programs designate a single module to collect globals; as long as this is expected,
it is not as harmful. |
In addition, programs that use multithreading to do parallel processing in Python commonly depend on global variables—they become shared memory
between functions running in parallel threads, and so act as a communication device.[†]
For now, though, especially if you are relatively new to programming, avoid the temptat... |
Six months from now, both you and your coworkers will be
happy you did.
###### Minimize Cross-File Changes
Here’s another scope-related issue: although we can change variables in another file
directly, we usually shouldn’t. |
Module files were introduced in Chapter 3 and are covered in more depth in the next part of this book. |
To illustrate their relationship to
scopes, consider these two module files:
_# first.py_
```
X = 99 # This code doesn't know about second.py
```
_# second.py_
```
import first
print(first.X) # Okay: references a name in another file
first.X = 88 # But changing it can be too subtle and imp... |
Because
all threaded functions run in the same process, global scopes often serve as shared memory between them.
Threading is commonly used for long-running tasks in GUIs, to implement nonblocking operations in general
and to leverage CPU capacity. |
It is also beyond this book’s scope; see the Python library manual, as well as
the follow-up texts listed in the Preface (such as O’Reilly’s Programming Python), for more details.
**|**
-----
The first defines a variable X, which the second prints and then changes by assignment.
Notice that we must import the first... |
That’s the main
point about modules: by segregating variables on a per-file basis, they avoid name
collisions across files.
Really, though, in terms of this chapter’s topic, the global scope of a module file be_comes the attribute namespace of the module object once it is imported—importers_
automatically have access ... |
Referencing the module’s variable to print it is fine—this is how modules
are linked together into a larger system normally. |
The problem with the assignment,
however, is that it is far too implicit: whoever’s charged with maintaining or reusing
the first module probably has no clue that some arbitrarily far-removed module on the
import chain can change X out from under him at runtime. |
In fact, the second module
may be in a completely different directory, and so difficult to notice at all.
Although such cross-file variable changes are always possible in Python, they are usually
much more subtle than you will want. |
Again, this sets up too strong a coupling between
the two files—because they are both dependent on the value of the variable `X, it’s`
difficult to understand or reuse one file without the other. |
Such implicit cross-file dependencies can lead to inflexible code at best, and outright bugs at worst.
Here again, the best prescription is generally to not do this—the best way to communicate across file boundaries is to call functions, passing in arguments and getting back
return values. |
In this specific case, we would probably be better off coding an accessor
_function to manage the change:_
_# first.py_
```
X = 99
def setX(new):
global X
X = new
```
_# second.py_
```
import first
first.setX(88)
```
This requires more code and may seem like a trivial change, but it makes a huge diff... |
In other words, it removes the element of surprise that
is rarely a good thing in software projects. |
Although we cannot prevent cross-file
changes from happening, common sense dictates that they should be minimized unless
widely accepted across the program.
**|**
-----
###### Other Ways to Access Globals
Interestingly, because global-scope variables morph into the attributes of a loaded
module object, we can emul... |
Code in this file
imports the enclosing module, first by name, and then by indexing the `sys.modules`
loaded modules table (more on this table in Chapter 21):
_# thismod.py_
```
var = 99 # Global variable == module attribute
def local():
var = 0 # Change local var
def glob1():
... |
It has
a cousin named nonlocal that can be used to change names in enclosing functions, too,
but to understand how that can be useful, we first need to explore enclosing functions
in general.
**|**
-----
###### Scopes and Nested Functions
So far, I’ve omitted one part of Python’s scope rules on purpose, because it... |
However, it’s time to take a deeper look at the letter
_E in the LEGB lookup rule. |
The E layer is fairly new (it was added in Python 2.2); it_
takes the form of the local scopes of any and all enclosing function `defs. |
Enclosing`
scopes are sometimes also called statically nested scopes. |
Really, the nesting is a lexical
one—nested scopes correspond to physically and syntactically nested code structures
in your program’s source code.
###### Nested Scope Details
With the addition of nested function scopes, variable lookup rules become slightly more
complex. |
Within a function:
- 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); and finally in the
built-in scope (the module builtins). |
global declarations make the search begin
in the global (module file) scope instead.
- An assignment (X = value) creates or changes the name X in the current local scope,
by default. |
If X is declared global within the function, the assignment creates or
changes the name X in the enclosing module’s scope instead. |
If, on the other hand,
```
X is declared nonlocal within the function, the assignment changes the name X in
```
the closest enclosing function’s local scope.
Notice that the global declaration still maps variables to the enclosing module. |
When
nested functions are present, variables in enclosing functions may be referenced, but
they require nonlocal declarations to be changed.
###### Nested Scope Examples
To clarify the prior section’s points, let’s illustrate with some real code. |
Here is what
an enclosing function scope looks like:
```
X = 99 # Global scope name: not used
def f1():
X = 88 # Enclosing def local
def f2():
print(X) # Reference made in nested def
f2()
f1() # Prints 88: enclosing def local
```
First off, this is legal Python cod... |
Here, the
**|**
-----
nested def runs while a call to the function f1 is running; it generates a function and
assigns it to the name f2, a local variable within f1’s local scope. |
In a sense, f2 is a
temporary function that lives only during the execution of (and is visible only to code
in) the enclosing f1.
But notice what happens inside f2: when it prints the variable X, it refers to the X that
lives in the enclosing f1 function’s local scope. |
Because functions can access names in
all physically enclosing def statements, the X in f2 is automatically mapped to the X in
```
f1, by the LEGB lookup rule.
```
This enclosing scope lookup works even if the enclosing function has already returned.
For example, the following code defines a function that makes and re... |
These terms refer to a function object that remembers values in
enclosing scopes regardless of whether those scopes are still present in memory. |
Although classes (described in Part VI of this book) are usually best at remembering state
because they make it explicit with attribute assignments, such functions provide an
alternative.
For instance, factory functions are sometimes used by programs that need to generate
event handlers on the fly in response to condi... |
Look at the following function, for example:
```
>>> def maker(N):
```
`... def action(X):` _# Make and return action_
`... return X ** N` _# action retains N from enclosing scope_
```
... |
return action
...
```
This defines an outer function that simply generates and returns a nested function,
without calling it. |
If we call the outer function:
`>>> f = maker(2)` _# Pass 2 to N_
```
>>> f
<function action at 0x014720B0>
```
**|**
-----
what we get back is a reference to the generated nested function—the one created by
running the nested def. |
If we now call what we got back from the outer function:
`>>> f(3)` _# Pass 3 to X, N remembers 2: 3 ** 2_
```
9
```
`>>> f(4)` _# 4 ** 2_
```
16
```
it invokes the nested function—the one called action within maker. |
The most unusual
part of this is that the nested function remembers integer 2, the value of the variable N
in maker, even though maker has returned and exited by the time we call action. |
In effect,
```
N from the enclosing local scope is retained as state information attached to action, and
```
we get back its argument squared.
If we now call the outer function again, we get back a new nested function with different
state information attached. |
That is, we get the argument cubed instead of squared, but
the original still squares as before:
`>>> g = maker(3)` _# g remembers 3, f remembers 2_
`>>> g(3)` _# 3 ** 3_
```
27
```
`>>> f(3)` _# 3 ** 2_
```
9
```
This works because each call to a factory function like this gets its own set of state
information. |
In our case, the function we assign to name g remembers 3, and f remembers 2, because each has its own state information retained by the variable N in maker.
This is an advanced technique that you’re unlikely to see very often in most code, except
among programmers with backgrounds in functional programming languages. |
On the
other hand, enclosing scopes are often employed by lambda function-creation expressions (discussed later in this chapter)—because they are expressions, they are almost
always nested within a def. |
Moreover, function nesting is commonly used for decora_tors (explored in Chapter 38)—in some cases, it’s the most reasonable coding pattern._
As a general rule, classes are better at “memory” like this because they make the state
retention explicit in attributes. |
Short of using classes, though, globals, enclosing scope
references like these, and default arguments are the main ways that Python functions
can retain state information. |
To see how they compete, Chapter 18 provides complete
coverage of defaults, but the next section gives enough of an introduction to get us
started.
###### Retaining enclosing scopes’ state with defaults
In earlier versions of Python, the sort of code in the prior section failed because nested
```
defs did not do anyt... |
Because
it skipped the scopes of enclosing functions, an error would result. |
To work around
this, programmers typically used default argument values to pass in and remember the
objects in an enclosing scope:
**|**
-----
```
def f1():
x = 88
def f2(x=x): # Remember enclosing scope X with defaults
print(x)
f2()
f1() # Prints 88
```
This code works in... |
In short, the syntax arg = val in a def header means that the argument
```
arg will default to the value val if no real value is passed to arg in a call.
```
In the modified f2 here, the x=x means that the argument x will default to the value of
```
x in the enclosing scope—because the second x is evaluated before Pyt... |
In effect, the default remembers what x was
in f1 (i.e., the object 88).
That’s fairly complex, and it depends entirely on the timing of default value evaluations.
In fact, the nested scope lookup rule was added to Python to make defaults unnecessary
for this role—today, Python automatically remembers any values requi... |
The following is an equivalent of
```
the prior example that banishes the notion of nesting. |
Notice the forward reference in
this code—it’s OK to call a function defined after the function that calls it, as long as
the second def runs before the first function is actually called. |
Code inside a def is never
evaluated until the function is actually called:
```
>>> def f1():
```
`... x = 88` _# Pass x along instead of nesting_
`... |
f2(x)` _# Forward reference okay_
```
...
>>> def f2(x):
... |
print(x)
...
>>> f1()
88
```
If you avoid nesting this way, you can almost forget about the nested scopes concept
in Python, unless you need to code in the factory function style discussed earlier—at
least, for def statements. |
lambdas, which almost naturally appear nested in defs, often
rely on nested scopes, as the next section explains.
###### Nested scopes and lambdas
While they’re rarely used in practice for defs themselves, you are more likely to care
about nested function scopes when you start coding `lambda expressions. |
We won’t`
cover lambda in depth until Chapter 19, but in short, it’s an expression that generates
a new function to be called later, much like a def statement. |
Because it’s an expression,
**|**
-----
though, it can be used in places that `def cannot, such as within list and dictionary`
literals.
Like a def, a lambda expression introduces a new local scope for the function it creates.
Thanks to the enclosing scopes lookup layer, lambdas can see all the variables that live... |
Thus, the following code works, but only
because the nested scope rules are applied:
```
def func():
x = 4
action = (lambda n: x ** n) # x remembered from enclosing def
return action
x = func()
print(x(2)) # Prints 16, 4 ** 2
```
Prior to the introduction of nested function scopes, ... |
For instance, the following
works on all Python releases:
```
def func():
x = 4
action = (lambda n, x=x: x ** n) # Pass x in manually
return action
```
Because `lambdas are expressions, they naturally (and even normally) nest inside en-`
closing defs. |
Hence, they are perhaps the biggest beneficiaries of the addition of enclosing function scopes in the lookup rules; in most cases, it is no longer necessary to
pass values into lambdas with defaults.
###### Scopes versus defaults with loop variables
There is one notable exception to the rule I just gave: if a lambda ... |
acts = []
```
`... for i in range(5):` _# Tries to remember each i_
`... acts.append(lambda x: i ** x)` _# All remember same last i!_
```
... |
return acts
...
>>> acts = makeActions()
>>> acts[0]
<function <lambda> at 0x012B16B0>
```
This doesn’t quite work, though—because the enclosing scope variable is looked up
when the nested functions are later called, they all effectively remember the same value
**|**
-----
(the value the loop variable had ... |
That is, we get back 4 to the
power of 2 for each function in the list, because i is the same in all of them:
`>>> acts[0](2)` _# All are 4 ** 2, value of last i_
```
16
```
`>>> acts[2](2)` _# This should be 2 ** 2_
```
16
```
`>>> acts[4](2)` _# This should be 4 ** 2_
```
16
```
This is the one case where w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.