Text stringlengths 1 9.41k |
|---|
Experiment with these on your own for more details. |
Developing further coding
alternatives is left as a suggested exercise (see also the sidebar “Why You Will Care:
One-Shot Iterations” for investigation of one such option).
###### Why You Will Care: One-Shot Iterations
In Chapter 14, we saw how some built-ins (like map) support only a single traversal and
are empty a... |
Now that we’ve studied a few more iteration
topics, I can make good on this promise. |
Consider the following clever alternative coding for this chapter’s zip emulation examples, adapted from one in Python’s manuals:
```
def myzip(*args):
iters = map(iter, args)
while iters:
res = [next(i) for i in iters]
yield tuple(res)
```
Because this code uses iter and next, it works... |
Note that there
is no reason to catch the StopIteration raised by the next(it) inside the comprehension
here when any one of the arguments’ iterators is exhausted—allowing it to pass ends
this generator function and has the same effect that a return statement would. |
The
```
while iters: suffices to loop if at least one argument is passed, and avoids an infinite
```
loop otherwise (the list comprehension would always return an empty list).
This code works fine in Python 2.6 as is:
```
>>> list(myzip('abc', 'lmnop'))
[('a', 'l'), ('b', 'm'), ('c', 'n')]
```
But it falls ... |
In 3.0, as soon as we’ve run the list
comprehension inside the loop once, iters will be empty (and res will be []) forever.
To make this work in 3.0, we need to use the list built-in function to create an object
that can support multiple iterations:
```
def myzip(*args):
iters = list(map(iter, args))
..... |
The lesson here: wrapping `map calls in`
```
list calls in 3.0 is not just for display!
```
**|**
-----
###### Value Generation in Built-in Types and Classes
Finally, although we’ve focused on coding value generators ourselves in this section,
don’t forget that many built-in types behave in similar ways—as we saw... |
print(key, D[key])
...
a 1
c 3
b 2
```
As we’ve also seen, for file iterators, Python simply loads lines from the file on demand:
```
>>> for line in open('temp.txt'):
... |
print(line, end='')
...
Tis but
a flesh wound.
```
While built-in type iterators are bound to a specific type of value generation, the concept
is similar to generators we code with expressions and functions. |
Iteration contexts like
```
for loops accept any iterable, whether user-defined or built-in.
```
Although beyond the scope of this chapter, it is also possible to implement arbitrary
user-defined generator objects with classes that conform to the iteration protocol. |
Such
classes define a special __iter__ method run by the iter built-in function that returns
an object having a __next__ method run by the next built-in function (a __getitem__
indexing method is also available as a fallback option for iteration).
The instance objects created from such a class are considered iterable ... |
With classes, though, we have access to
richer logic and data structuring options than other generator constructs can offer.
The iterator story won’t really be complete until we’ve seen how it maps to classes, too.
For now, we’ll have to settle for postponing its conclusion until we study class-based
iterators in Chap... |
We met these briefly in Chapters
5 and 8, but with our new knowledge of comprehensions and generators, you should
now be able to grasp these 3.0 extensions in full:
- For sets, the new literal form {1, 3, 2} is equivalent to set([1, 3, 2]), and the
new set comprehension syntax {f(x) for x in S if P(x)} is like the ge... |
The last two are new
and are not available in 2.6:
`>>> [x * x for x in range(10)]` _# List comprehension: builds list_
```
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # like list(generator expr)
```
`>>> (x * x for x in range(10))` _# Generator expression: produces items_
```
<generator object at 0x009E7328> # Pa... |
Because both accept any iterable, a generator
works well here:
`>>> {x * x for x in range(10)}` _# Comprehension_
```
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
```
`>>> set(x * x for x in range(10))` _# Generator and type name_
```
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> {x: x * x for x in range(10)}
{0: 0, 1: 1,... |
Here are statement-based equivalents of the last two comprehensions:
**|**
-----
```
>>> res = set()
```
`>>> for x in range(10):` _# Set comprehension equivalent_
```
... |
res.add(x * x)
...
>>> res
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> res = {}
```
`>>> for x in range(10):` _# Dict comprehension equivalent_
```
... |
res[x] = x * x
...
>>> res
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
```
Notice that although both forms accept iterators, they have no notion of generating
results on demand—both forms build objects all at once. |
If you mean to produce keys
and values upon request, a generator expression is more appropriate:
```
>>> G = ((x, x * x) for x in range(10))
>>> next(G)
(0, 0)
>>> next(G)
(1, 1)
###### Extended Comprehension Syntax for Sets and Dictionaries
```
Like list comprehensions and generator expressions, both set a... |
They may or may not have
a performance advantage over the generator or `for loop alternatives, but we would`
have to time their performance explicitly to be sure—which seems a natural segue to
the next section.
###### Timing Iteration Alternatives
We’ve met quite a few iteration alternatives in this book. |
To summarize, let’s work
through a larger case study that pulls together some of the things we’ve learned about
iteration and functions.
I’ve mentioned a few times that list comprehensions have a speed performance advantage over `for loop statements, and that` `map performance can be better or worse`
depending on call... |
The generator expressions of the prior sections tend to be
slightly slower than list comprehensions, though they minimize memory space
requirements.
All that’s true today, but relative performance can vary over time because Python’s
internals are constantly being changed and optimized. |
If you want to verify their performance for yourself, you need to time these alternatives on your own computer and
your own version of Python.
###### Timing Module
Luckily, Python makes it easy to time code. |
To see how the iteration options stack up,
let’s start with a simple but general timer utility function coded in a module file, so it
can be used in a variety of programs:
_# File mytimer.py_
```
import time
reps = 1000
repslist = range(reps)
def timer(func, *pargs, **kargs):
start = time.clock()
for i... |
Points to notice:
- Python’s time module gives access to the current time, with precision that varies
per platform. |
On Windows, this call is claimed to give microsecond granularity
and so is very accurate.
- The `range call is hoisted out of the timing loop, so its construction cost is not`
charged to the timed function in Python 2.6. |
In 3.0 range is an iterator, so this step
isn’t required (but doesn’t hurt).
- The reps count is a global that importers can change if needed: mytimer.reps = N.
When complete, the total elapsed time for all calls is returned in a tuple, along with the
timed function’s final return value so callers can verify its ope... |
You’ll learn more about modules
and imports in the next part of this book, but you’ve already seen enough of the basics
to make sense of this code—simply import the module and call the function to use this
file’s timer (and see Chapter 3’s coverage of module attributes if you need a refresher).
###### Timing Script
N... |
In Python 3.0 (only) we must do
the same for the map result, since it is now an iterable object as well. |
Also notice how
the code at the bottom steps through a tuple of four function objects and prints the
```
__name__ of each: as we’ve seen, this is a built-in attribute that gives a function’s name.
###### Timing Results
```
When the script of the prior section is run under Python 3.0, I get the following results
on my... |
Although wrapping a generator expression
in a list call makes it functionally equivalent to a square-bracketed list comprehension,
the internal implementations of the two expressions appear to differ (though we’re also
effectively timing the list call for the generator test):
```
return [abs(x) for x in range(size)] ... |
I didn’t test
generator functions then, and the output format wasn’t quite as grandiose:
```
2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
forStatement => 6.10899996758
listComprehension => 3.51499986649
mapFunction => 2.73399996758
generatorExpression => 4.11600017548
```
The f... |
In fact, all the 2.6 results for this script are slightly
quicker than 3.0 on this same machine if the list call is removed from the map test to
avoid creating the results list twice (try this on your own to verify).
Watch what happens, though, if we change this script to perform a real operation on
each iteration, su... |
On Python 3.0:
```
C:\misc> c:\python30\python timeseqs.py
3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)]
```
**|**
-----
```
-------------------------------- forLoop : 2.60754 => [10...10009]
-------------------------------- listComp : 1.57585 => [10...10009]
--------------------... |
It’s virtually impossible to guess which method will
perform the best—the best you can do is time your own code, on your computer, with
your version of Python. |
In this case, all we should say for certain is that on this Python,
using a user-defined function in map calls can slow performance by at least a factor of
2, and that list comprehensions run quickest for this test.
As I’ve mentioned before, however, performance should not be your primary concern
when writing Python c... |
Write for readability and simplicity first, then optimize
later, if and only if needed. |
It could very well be that any of the five alternatives is quick
enough for the data sets your program needs to process; if so, program clarity should
be the chief goal.
###### Timing Module Alternatives
The timing module of the prior section works, but it’s a bit primitive on multiple fronts:
- It always uses the ... |
While that option is best on Windows, the time.time call may provide better resolution on some Unix platforms.
- Adjusting the number of repetitions requires changing module-level globals—a
less than ideal arrangement if the timer function is being used and shared by multiple importers.
- As is, the timer works by ... |
To
account for random system load fluctuations, it might be better to select the best
time among all the tests, instead of the total time.
The following alternative implements a more sophisticated timer module that addresses
all three points by selecting a timer call based on platform, allowing the repeat count
**|**... |
It uses dictionary pop operations to remove the _reps argument from arguments intended for the
test function and provide it with a default, and it traces arguments during development
if you change its trace function to print. |
To test with this new timer module on either
Python 3.0 or 2.6, change the timing script as follows (the omitted code in the test
functions of this version use the x + 1 operation for each test, as coded in the prior
section):
_# File timeseqs.py_
```
import sys, mytimer
reps = 10000
repslist = range(reps)
def... |
The results on my machine are as follows:
```
C:\misc> c:\python30\python timeseqs.py
3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)]
<timer>
---------------------------------- forLoop : 2.35371 => [10...10009]
---------------------------------- listComp : 1.29640 => [10...10009]
---... |
At least in
terms of relative performance, list comprehensions appear best in most cases; map is
only slightly better when built-ins are applied.
**|**
-----
###### Using keyword-only arguments in 3.0
We can also make use of Python 3.0 keyword-only arguments here to simplify the timer
module’s code. |
As we learned in Chapter 19, keyword-only arguments are ideal for
configuration options such as our functions’ _reps argument. |
They must be coded after
a * and before a ** in the function header, and in a function call they must be passed
by keyword and appear before the ** if used. |
Here’s a keyword-only-based alternative
to the prior module. |
Though simpler, it compiles and runs under Python 3.X only, not
2.6:
_# File mytimer.py (3.X only)_
```
"""
Use 3.0 keyword-only default arguments, instead of ** and dict pops.
No need to hoist range() out of test in 3.0: a generator, not a list
"""
import time, sys
trace = lambda *args: None # or print
... |
The timer’s
results can help you judge relative speeds of coding alternatives, though, and may be
more meaningful for longer-running operations like the following—calculating 2 to the
power one million takes an order of magnitude (power of 10) longer than the preceding
```
2**100,000:
```
`>>> timer(power, 2, 1000000,... |
If
you want to compare 2.X and 3.X speed, for example, or support programmers using
either Python line, the prior version is likely a better choice. |
If you’re using Python 2.6,
the above session runs the same with the prior version of the timer module.
###### Other Suggestions
For more insight, try modifying the repetition counts used by these modules, or explore
the alternative timeit module in Python’s standard library, which automates timing of
code, supports ... |
In general, you should profile code to isolate bottlenecks before recoding and timing alternatives as we’ve done here.
**|**
-----
It might be useful as well to experiment with using the new `str.format method in`
Python 2.6 and 3.0 instead of the % formatting expression (which could potentially be
deprecated in th... |
Since using them is much less common in Python
programs than building lists of results, we’ll leave this task in the suggested exercise
column (and please, no wagering...).
Finally, keep the timing module we wrote here filed away for future reference—we’ll
repurpose it to measure performance of alternative numeric squ... |
If you’re interested in pursuing this topic further,
we’ll also experiment with techniques for timing dictionary comprehensions versus
```
for loops interactively.
###### Function Gotchas
```
Now that we’ve reached the end of the function story, let’s review some common pitfalls. |
Functions have some jagged edges that you might not expect. |
They’re all obscure,
and a few have started to fall away from the language completely in recent releases, but
most have been known to trip up new users.
###### Local Names Are Detected Statically
As you know, Python classifies names assigned in a function as locals by default; they
live in the function’s scope and ex... |
What you may
not realize is that Python detects locals statically, when it compiles the def’s code, rather
than by noticing assignments as they happen at runtime. |
This leads to one of the most
common oddities posted on the Python 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()
99
```
Here, the X in the function resolves to the X in the module. |
But watch what happens if
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 for "import X", "def X"...
>>> selector()
...error text omitted...
UnboundLocalError: local variable 'X' referenced before assignment
```
You get the name usage error shown here, but the reason is subtle. |
Python reads and
compiles this code when it’s typed interactively or imported from a module. |
While
compiling, Python sees the assignment to `X and decides that` `X will be a local name`
everywhere in the function. |
But when the function is actually run, because the assignment hasn’t yet happened when the print executes, Python says you’re using an undefined name. |
According to its name rules, it should say this; the local X is used before
being assigned. In fact, any assignment in a function body makes a name local. |
Imports,
```
=, nested defs, nested classes, and so on are all susceptible to this behavior.
```
The problem occurs because assigned names are treated as locals everywhere in a function, not just after the statements where they are assigned. |
Really, the previous example
is ambiguous at best: was the intention to print the global X and then create a local X,
or is this a genuine programming error? |
Because Python treats X as a local everywhere,
it is viewed as an error; if you really mean to print the global X, you need to declare it
in a global statement:
```
>>> def selector():
```
`... |
global X` _# Force X to be global (everywhere)_
```
... print(X)
... |
X = 88
...
>>> selector()
99
```
Remember, though, that this means the assignment also changes the global X, not a
local X. |
Within a function, you can’t use both local and global versions of the same
simple name. |
If you really meant to print the global and then set a local of the same
name, you’d need to import the enclosing module and use module attribute notation
to get to the global version:
```
>>> X = 99
>>> def selector():
```
`... |
import __main__` _# Import enclosing module_
`... print(__main__.X)` _# Qualify to get to global version of name_
`... X = 88` _# Unqualified X classified as local_
**|**
-----
`... |
print(X)` _# Prints local version of name_
```
...
>>> selector()
99
88
```
Qualification (the .X part) fetches a value from a namespace object. |
The interactive
namespace is a module called __main__, so __main__.X reaches the global version of X.
If that isn’t clear, check out Chapter 17.
In recent versions Python has improved on this story somewhat by issuing for this case
the more specific “unbound local” error message shown in the example listing (it used
t... |
Internally, Python saves one object per default argument
attached to the function itself.
That’s usually what you want—because defaults are evaluated at def time, it lets you
save values from the enclosing scope, if needed. |
But because a default retains an object
between calls, you have to be careful about changing mutable defaults. |
For instance,
the following function uses an empty list as a default value, and then changes it in-place
each time the function is called:
`>>> def saver(x=[]):` _# Saves away a list object_
`... |
x.append(1)` _# Changes same object each time!_
```
... |
print(x)
...
```
`>>> saver([2])` _# Default not used_
```
[2, 1]
```
`>>> saver()` _# Default used_
```
[1]
```
`>>> saver()` _# Grows on each call!_
```
[1, 1]
>>> saver()
[1, 1, 1]
```
Some see this behavior as a feature—because mutable default arguments retain their
state between function calls, the... |
In a sense, they work sort of like global variables, but
their names are local to the functions and so will not clash with names elsewhere in a
program.
To most observers, though, this seems like a gotcha, especially the first time they run
into it. |
There are better ways to retain state between calls in Python (e.g., using classes,
which will be discussed in Part VI).
Moreover, mutable defaults are tricky to remember (and to understand at all). |
They
depend upon the timing of default object construction. In the prior example, there is
**|**
-----
just one list object for the default value—the one created when the def is executed. |
You
don’t get a new list every time the function is called, so the list grows with each new
append; it is not reset to empty on each call.
If that’s not the behavior you want, simply make a copy of the default at the start of
the function body, or move the default value expression into the function body. |
As long
as the value resides in code that’s actually executed each time the function runs, you’ll
get a new object each time through:
```
>>> def saver(x=None):
```
`... |
if x is None:` _# No argument passed?_
`... x = []` _# Run code to make a new list_
`... x.append(1)` _# Changes new list object_
```
... |
print(x)
...
>>> saver([2])
[2, 1]
```
`>>> saver()` _# Doesn't grow here_
```
[1]
>>> saver()
[1]
```
By the way, the if statement in this example could almost be replaced by the assignment
```
x = x or [], which takes advantage of the fact that Python’s or returns one of its
```
operand objects: if no ... |
If an empty list were passed in, the or expression
would cause the function to extend and return a newly created list, rather than extending and returning the passed-in list like the if version. |
(The expression becomes
```
[] or [], which evaluates to the new empty list on the right; see the section “Truth
```
Tests” on page 320 if you don’t recall why). |
Real program requirements may call for
either behavior.
Today, another way to achieve the effect of mutable defaults in a possibly less confusing
way is to use the function attributes we discussed in Chapter 19:
```
>>> def saver():
... |
saver.x.append(1)
... |
print(saver.x)
...
>>> saver.x = []
>>> saver()
[1]
>>> saver()
[1, 1]
>>> saver()
[1, 1, 1]
```
The function name is global to the function itself, but it need not be declared because
it isn’t changed directly within the function. |
This isn’t used in exactly the same way,
**|**
-----
but when coded like this, the attachment of an object to the function is much more
explicit (and arguably less magical).
###### Functions Without returns
In Python functions, `return (and` `yield) statements are optional. |
When a function`
doesn’t return a value explicitly, the function exits when control falls off the end of the
function body. |
Technically, all functions return a value; if you don’t provide a return
statement, your function returns the None object automatically:
```
>>> def proc(x):
```
`... |
print(x)` _# No return is a None return_
```
...
>>> x = proc('testing 123...')
testing 123...
>>> print(x)
None
```
Functions such as this without a `return are Python’s equivalent of what are called`
“procedures” in some languages. |
They’re usually invoked as statements, and the None
results are ignored, as they do their business without computing a useful result.
This is worth knowing, because Python won’t tell you if you try to use the result of a
function that doesn’t return one. |
For instance, assigning the result of a list `append`
method won’t raise an error, but you’ll get back None, not the modified list:
```
>>> list = [1, 2, 3]
```
`>>> list = list.append(4)` _# append is a "procedure"_
`>>> print(list)` _# append changes list in-place_
```
None
```
As mentioned in “Common Coding Go... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.