Text stringlengths 1 9.41k |
|---|
Use defaults to save loop variable values instead (see_ Chapter 17 for more details on this topic).
###### Chapter Summary
This chapter wrapped up our coverage of built-in comprehension and iteration tools.
It explored list comprehensions in the context of functional tools and presented generator functions and expres... |
As a finale, we
**|**
-----
also measured the performance of iteration alternatives, and we closed with a review
of common function-related mistakes to help you avoid pitfalls.
This concludes the functions part of this book. |
In the next part, we will study modules—
the topmost organizational structure in Python, and the structure in which our functions always live. |
After that, we will explore classes, tools that are largely packages of
functions with special first arguments. |
As we’ll see, user-defined classes can implement
objects that tap into the iteration protocol, just like the generators and iterables we met
here. |
Everything we have learned in this part of the book will apply when functions
pop up later in the context of class methods.
Before moving on to modules, though, be sure to work through this chapter’s quiz and
the exercises for this part of the book, to practice what we’ve learned about functions
here.
###### Test You... |
What is the difference between enclosing a list comprehension in square brackets
and parentheses?
2. How are generators and iterators related?
3. |
How can you tell if a function is a generator function?
4. What does a yield statement do?
5. How are map calls and list comprehensions related? |
Compare and contrast the two.
###### Test Your Knowledge: Answers
1. List comprehensions in square brackets produce the result list all at once in memory. |
When they are enclosed in parentheses instead, they are actually generator
expressions—they have a similar meaning but do not produce the result list all at
once. |
Instead, generator expressions return a generator object, which yields one
item in the result at a time when used in an iteration context.
2. |
Generators are objects that support the iteration protocol—they have a __next__
method that repeatedly advances to the next item in a series of results and raises
an exception at the end of the series. |
In Python, we can code generator functions
with def, generator expressions with parenthesized list comprehensions, and generator objects with classes that define a special method named __iter__ (discussed
later in the book).
3. |
A generator function has a `yield statement somewhere in its code. |
Generator`
functions are otherwise identical to normal functions syntactically, but they are
compiled specially by Python so as to return an iterable object when called.
**|**
-----
4. |
When present, this statement makes Python compile the function specially as a
generator; when called, the function returns a generator object that supports the
iteration protocol. |
When the yield statement is run, it sends a result back to the
caller and suspends the function’s state; the function can then be resumed after the
last yield statement, in response to a next built-in or __next__ method call issued
by the caller. |
Generator functions may also have a return statement, which terminates the generator.
5. |
The map call is similar to a list comprehension—both build a new list by collecting
the results of applying an operation to each item in a sequence or other iterable,
one item at a time. |
The main difference is that map applies a function call to each
item, and list comprehensions apply arbitrary expressions. |
Because of this, list
comprehensions are more general; they can apply a function call expression like
```
map, but map requires a function to apply other kinds of expressions. |
List compre
```
hensions also support extended syntax such as nested for loops and if clauses that
subsume the filter built-in.
###### Test Your Knowledge: Part IV Exercises
In these exercises, you’re going to start coding more sophisticated programs. |
Be sure
to check the solutions in “Part IV, Functions” on page 1111 in Appendix B, and be
sure to start writing your code in module files. |
You won’t want to retype these exercises
from scratch if you make a mistake.
1. The basics. |
At the Python interactive prompt, write a function that prints its single
argument to the screen and call it interactively, passing a variety of object types:
string, integer, list, dictionary. |
Then, try calling it without passing any argument.
What happens? What happens when you pass two arguments?
2. Arguments. Write a function called adder in a Python module file. |
The function
should accept two arguments and return the sum (or concatenation) of the two.
Then, add code at the bottom of the file to call the adder function with a variety of
object types (two strings, two lists, two floating points), and run this file as a script
from the system command line. |
Do you have to print the call statement results to
see results on your screen?
3. varargs. |
Generalize the adder function you wrote in the last exercise to compute
the sum of an arbitrary number of arguments, and change the calls to pass more
or fewer than two arguments. |
What type is the return value sum? |
(Hints: a slice
such as S[:0] returns an empty sequence of the same type as S, and the type builtin function can test types; but see the manually coded `min examples in` Chapter 18 for a simpler approach.) What happens if you pass in arguments of different
types? |
What about passing in dictionaries?
**|**
-----
4. Keywords. Change the adder function from exercise 2 to accept and sum/concatenate three arguments: def adder(good, bad, ugly). |
Now, provide default values
for each argument, and experiment with calling the function interactively. Try
passing one, two, three, and four arguments. Then, try passing keyword arguments. |
Does the call adder(ugly=1, good=2) work? Why? Finally, generalize the
new adder to accept and sum/concatenate an arbitrary number of keyword arguments. |
This is similar to what you did in exercise 3, but you’ll need to iterate over
a dictionary, not a tuple. |
(Hint: the dict.keys method returns a list you can step
through with a for or while, but be sure to wrap it in a list call to index it in 3.0!)
5. |
Write a function called `copyDict(dict) that copies its dictionary argument. It`
should return a new dictionary containing all the items in its argument. |
Use the
dictionary keys method to iterate (or, in Python 2.2, step over a dictionary’s keys
without calling keys). |
Copying sequences is easy (X[:] makes a top-level copy);
does this work for dictionaries, too?
6. Write a function called `addDict(dict1, dict2) that computes the union of two`
dictionaries. |
It should return a new dictionary containing all the items in both its
arguments (which are assumed to be dictionaries). |
If the same key appears in both
arguments, feel free to pick a value from either. Test your function by writing it in
a file and running the file as a script. |
What happens if you pass lists instead of
dictionaries? |
How could you generalize your function to handle this case, too?
(Hint: see the type built-in function used earlier.) Does the order of the arguments
passed in matter?
7. |
More argument-matching examples. |
First, define the following six functions (either
interactively or in a module file that can be imported):
```
def f1(a, b): print(a, b) # Normal args
def f2(a, *b): print(a, b) # Positional varargs
def f3(a, **b): print(a, b) # Keyword varargs
def f4(a, *b, **c): print(a, b, c) # Mixed m... |
Do you think mixing matching modes is a good idea in general? |
Can you
think of cases where it would be useful?
```
>>> f1(1, 2)
>>> f1(b=2, a=1)
>>> f2(1, 2, 3)
>>> f3(1, x=2, y=3)
>>> f4(1, 2, 3, x=2, y=3)
```
**|**
-----
```
>>> f5(1)
>>> f5(1, 4)
>>> f6(1)
>>> f6(1, 3, 4)
```
8. |
Primes revisited. |
Recall the following code snippet from Chapter 13, which simplistically determines whether a positive integer is prime:
```
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
else:... |
While
you’re at it, experiment with replacing the first line’s // operator with / to see how
true division changes the / operator in Python 3.0 and breaks this code (refer back
to Chapter 5 if you need a refresher). |
What can you do about negatives, and the
values 0 and 1? How about speeding this up? |
Your outputs should look something
like this:
```
13 is prime
13.0 is prime
15 has factor 5
15.0 has factor 5.0
```
9. List comprehensions. |
Write code to build a new list containing the square roots of
all the numbers in this list: [2, 4, 9, 16, 25]. Code this as a for loop first, then
as a map call, and finally as a list comprehension. |
Use the sqrt function in the builtin math module to do the calculation (i.e., import math and say math.sqrt(x)). Of
the three, which approach do you like best?
10. Timing tools. |
In Chapter 5, we saw three ways to compute square roots:
```
math.sqrt(X), X ** .5, and pow(X, .5). If your programs run a lot these, their
```
relative performance might become important. |
To see which is quickest, repurpose
the timerseqs.py script we wrote in this chapter to time each of these three tools.
Use the mytimer.py timer module with the best function (you can use either the
3.0-ony keyword-only variant, or the 2.6/3.0 version). |
You might also want to
repackage the testing code in this script for better reusability—by passing a test
functions tuple to a general tester function, for example (for this exercise a
copy-and-modify approach is fine). |
Which of the three square root tools seems to
run fastest on your machine and Python in general? |
Finally, how might you go
about interactively timing the speed of dictionary comprehensions versus `for`
loops?
**|**
-----
##### PART V
## Modules
-----
-----
###### CHAPTER 21
### Modules: The Big Picture
This chapter begins our in-depth look at the Python module, the highest-level program
organization unit,... |
In concrete terms,
modules usually correspond to Python program files (or extensions coded in external
languages such as C, Java, or C#). |
Each file is a module, and modules import other
modules to use the names they define. |
Modules are processed with two statements and
one important function:
```
import
```
Lets a client (importer) fetch a module as a whole
```
from
```
Allows clients to fetch particular names from a module
```
imp.reload
```
Provides a way to reload a module’s code without stopping Python
Chapter 3 introduced module ... |
This first chapter offers a general look at the
role of modules in overall program structure. |
In the following chapters, we’ll dig into
the coding details behind the theory.
Along the way, we’ll flesh out module details omitted so far: you’ll learn about reloads,
the __name__ and __all__ attributes, package imports, relative import syntax, and so
on. |
Because modules and classes are really just glorified namespaces, we’ll formalize
namespace concepts here as well.
###### Why Use Modules?
In short, modules provide an easy way to organize components into a system by serving
as self-contained packages of variables known as namespaces. |
All the names defined at
the top level of a module file become attributes of the imported module object. |
As we
saw in the last part of this book, imports give access to names in a module’s global
-----
scope. |
That is, the module file’s global scope morphs into the module object’s attribute
namespace when it is imported. |
Ultimately, Python’s modules allow us to link individual files into a larger program system.
More specifically, from an abstract perspective, modules have at least three roles:
_Code reuse_
As discussed in Chapter 3, modules let you save code in files permanently. |
Unlike
code you type at the Python interactive prompt, which goes away when you exit
Python, code in module files is persistent—it can be reloaded and rerun as many
times as needed. |
More to the point, modules are a place to define names, known
as attributes, which may be referenced by multiple external clients.
_System namespace partitioning_
Modules are also the highest-level program organization unit in Python. |
Fundamentally, they are just packages of names. |
Modules seal up names into
self-contained packages, which helps avoid name clashes—you can never see a
name in another file, unless you explicitly import that file. |
In fact, everything “lives”
in a module—code you execute and objects you create are always implicitly enclosed in modules. |
Because of that, modules are natural tools for grouping system
components.
_Implementing shared services or data_
From an operational perspective, modules also come in handy for implementing
components that are shared across a system and hence require only a single copy.
For instance, if you need to provide a global ob... |
In practice, programs usually involve more than just one file; for all
but the simplest scripts, your programs will take the form of multifile systems. |
And
even if you can get by with coding a single file yourself, you will almost certainly wind
up using external files that someone else has already written.
This section introduces the general architecture of Python programs—the way you
divide a program into a collection of source files (a.k.a. |
modules) and link the parts
into a whole. |
Along the way, we’ll also explore the central concepts of Python modules,
imports, and object attributes.
**|**
-----
###### How to Structure a Program
Generally, a Python program consists of multiple text files containing Python state_ments. |
The program is structured as one main, top-level file, along with zero or more_
supplemental files known as modules in Python.
In Python, the top-level (a.k.a. |
script) file contains the main flow of control of your
program—this is the file you run to launch your application. |
The module files are
libraries of tools used to collect components used by the top-level file (and possibly
elsewhere). |
Top-level files use tools defined in module files, and modules use tools
defined in other modules.
Module files generally don’t do anything when run directly; rather, they define tools
intended for use in other files. |
In Python, a file imports a module to gain access to the
tools it defines, which are known as its attributes (i.e., variable names attached to objects such as functions). |
Ultimately, we import modules and access their attributes to
use their tools.
###### Imports and Attributes
Let’s make this a bit more concrete. |
Figure 21-1 sketches the structure of a Python
program composed of three files: a.py, b.py, and c.py. |
The file a.py is chosen to be the
top-level file; it will be a simple text file of statements, which is executed from top to
bottom when launched. |
The files b.py and c.py are modules; they are simple text files
of statements as well, but they are not usually launched directly. |
Instead, as explained
previously, modules are normally imported by other files that wish to use the tools they
define.
_Figure 21-1. Program architecture in Python. A program is a system of modules. |
It has one top-level_
_script file (launched to run the program), and multiple module files (imported libraries of tools). |
Scripts_
_and modules are both text files containing Python statements, though the statements in modules_
_usually just create objects to be used later. |
Python’s standard library provides a collection of precoded_
_modules._
**|**
-----
For instance, suppose the file b.py in Figure 21-1 defines a function called spam, for
external use. |
As we learned when studying functions in Part IV, b.py will contain a
Python def statement to generate the function, which can later be run by passing zero
or more values in parentheses after the function’s name:
```
def spam(text):
print(text, 'spam')
```
Now, suppose a.py wants to use spam. |
To this end, it might contain Python statements
such as the following:
```
import b
b.spam('gumby')
```
The first of these, a Python import statement, gives the file a.py access to everything
defined by top-level code in the file b.py. |
It roughly means “load the file b.py (unless
it’s already loaded), and give me access to all its attributes through the name `b.”`
```
import (and, as you’ll see later, from) statements execute and load other files at runtime.
```
In Python, cross-file module linking is not resolved until such import statements are
ex... |
In fact, the module name used in an import statement serves
two purposes: it identifies the external file to be loaded, but it also becomes a variable
assigned to the loaded module. |
Objects defined by a module are also created at runtime,
as the import is executing: import literally runs statements in the target file one at a time
to create its contents.
The second of the statements in a.py calls the function spam defined in the module b,
using object attribute notation. |
The code b.spam means “fetch the value of the name
```
spam that lives within the object b.” This happens to be a callable function in our ex
```
ample, so we pass a string in parentheses ('gumby'). |
If you actually type these files, save
them, and run a.py, the words “gumby spam” will be printed.
You’ll see the object.attribute notation used throughout Python scripts—most objects have useful attributes that are fetched with the “.” operator. |
Some are callable
things like functions, and others are simple data values that give object properties (e.g.,
a person’s name).
The notion of importing is also completely general throughout Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.