Text
stringlengths
1
9.41k
In Part VII, you will learn that you can catch exceptions using try statements and process them arbitrarily; you’ll also see there that Python includes a full-blown source code debugger for special error-detection requirements.
For now, notice that Python gives meaningful messages when programming errors occur, instead of crashing silently: ``` % python >>> 2 ** 500 32733906078961418700131896968275991522166420460430647894832913680961337964046745 54883270092325904157150886684127560071009217256545885393053328527589376 >>> ...
Breaks and cycles. When you type this code: ``` L = [1, 2] L.append(L) ``` you create a cyclic data structure in Python.
In Python releases before 1.5.1, the Python printer wasn’t smart enough to detect cycles in objects, and it would print an unending stream of [1, 2, [1, 2, [1, 2, [1, 2, and so on, until you hit the break-key combination on your machine (which, technically, raises a keyboardinterrupt exception that prints a default mes...
Beginning with Python 1.5.1, **|** **f** ----- the printer is clever enough to detect cycles and prints [[...]] instead to let you know that it has detected a loop in the object’s structure and avoided getting stuck printing forever. The reason for the cycle is subtle and requires information you will glean in Part...
But in short, assignments in Python always generate _references to objects, not copies of them. You can think of objects as_ chunks of memory and of references as implicitly followed pointers.
When you run the first assignment above, the name L becomes a named reference to a two-item list object—a pointer to a piece of memory.
Python lists are really arrays of object references, with an append method that changes the array in-place by tacking on another object reference at the end.
Here, the append call adds a reference to the front of L at the end of L, which leads to the cycle illustrated in Figure B-1: a pointer at the end of the list that points back to the front of the list. Besides being printed specially, as you’ll learn in Chapter 6 cyclic objects must also be handled specially by Python’...
Though rare in practice, in some programs that traverse arbitrary objects or structures you might have to detect such cycles yourself by keeping track of where you’ve been to avoid looping.
Believe it or not, cyclic data structures can sometimes be useful, despite their special-case printing. _Figure B-1. A cyclic object, created by appending a list to itself.
By default, Python appends a reference_ _to the original list, not a copy of the list._ ###### Part II, Types and Operations See “Test Your Knowledge: Part II Exercises” on page 255 in Chapter 9 for the exercises. 1.
The basics. Here are the sorts of results you should get, along with a few comments about their meaning.
Again, note that ; is used in a few of these to squeeze more than one statement onto a single line (the ; is a statement separator), and commas **|** ----- build up tuples displayed in parentheses.
Also keep in mind that the `/ division` result near the top differs in Python 2.6 and 3.0 (see Chapter 5 for details), and the ``` list wrapper around dictionary method calls is needed to display results in 3.0, ``` but not 2.6 (see Chapter 8): _# Numbers_ `>>> 2 ** 16` _# 2 raised to the power 16_ ``` 65536 ``` ...
Indexing and slicing.
Indexing out of bounds (e.g., L[4]) raises an error; Python always checks to make sure that all offsets are within the bounds of a sequence. On the other hand, slicing out of bounds (e.g., L[-1000:100]) works because Python scales out-of-bounds slices so that they always fit (the limits are set to zero and the sequence...
You get back an empty slice ([ ]) because Python scales the slice limits to make sure that the lower bound is always less than or equal to the upper bound (e.g., L[3:1] is scaled to L[3:3], the empty insertion point at offset 3).
Python slices are always extracted from left to right, even if you use negative indexes (they are first converted to positive indexes by adding the sequence length).
Note that Python 2.3’s three-limit slices modify this behavior somewhat.
For instance, L[3:1:-1] does extract from right to left: ``` >>> L = [1, 2, 3, 4] >>> L[4] Traceback (innermost last): File "<stdin>", line 1, in ? IndexError: list index out of range >>> L[-1000:100] [1, 2, 3, 4] >>> L[3:1] [] >>> L [1, 2, 3, 4] >>> L[3:1] = ['?'] >...
Indexing, slicing, and del. Your interaction with the interpreter should look something like the following code.
Note that assigning an empty list to an offset stores an empty list object there, but assigning an empty list to a slice deletes the slice. Slice assignment expects another sequence, or you’ll get a type error; it inserts items _inside the sequence assigned, not the sequence itself:_ **|** ----- ``` >>> L = [1,...
Tuple assignment. The values of X and Y are swapped.
When tuples appear on the left and right of an assignment symbol (=), Python assigns objects on the right to targets on the left according to their positions.
This is probably easiest to understand by noting that the targets on the left aren’t a real tuple, even though they look like one; they are simply a set of independent assignment targets.
The items on the right are a tuple, which gets unpacked during the assignment (the tuple provides the temporary assignment needed to achieve the swap effect): ``` >>> X = 'spam' >>> Y = 'eggs' >>> X, Y = Y, X >>> X 'eggs' >>> Y 'spam' ``` 5.
Dictionary keys. Any immutable object can be used as a dictionary key, including integers, tuples, strings, and so on.
This really is a dictionary, even though some of its keys look like integer offsets.
Mixed-type keys work fine, too: ``` >>> D = {} >>> D[1] = 'a' >>> D[2] = 'b' >>> D[(1, 2, 3)] = 'c' >>> D {1: 'a', 2: 'b', (1, 2, 3): 'c'} ``` 6. Dictionary indexing.
Indexing a nonexistent key (D['d']) raises an error; assigning to a nonexistent key (D['d']='spam') creates a new dictionary entry.
On the other hand, out-of-bounds indexing for lists raises an error too, but so do out-of-bounds assignments.
Variable names work like dictionary keys; they must have already been assigned when referenced, but they are created when first assigned.
In fact, variable names can be processed as dictionary keys if you wish (they’re made visible in module namespace or stack-frame dictionaries): **|** **f** ----- ``` >>> D = {'a':1, 'b':2, 'c':3} >>> D['a'] 1 >>> D['d'] Traceback (innermost last): File "<stdin>", line 1, in ? KeyError: ...
Generic operations.
Question answers: - The + operator doesn’t work on different/mixed types (e.g., string + list, list + tuple). - + doesn’t work for dictionaries, as they aren’t sequences. - The append method works only for lists, not strings, and keys works only on dictionaries.
append assumes its target is mutable, since it’s an in-place extension; strings are immutable. - Slicing and concatenation always return a new object of the same type as the objects processed: ``` >>> "x" + 1 Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: illegal argument ty...
String indexing. This is a bit of a trick question—Because strings are collections of one-character strings, every time you index a string, you get back a string that can be indexed again.
S[0][0][0][0][0] just keeps indexing the first character over and over.
This generally doesn’t work for lists (lists can hold arbitrary objects) unless the list contains strings: ``` >>> S = "spam" >>> S[0][0][0][0][0] 's' >>> L = ['s', 'p'] >>> L[0][0][0] 's' ``` 9.
Immutable types. Either of the following solutions works.
Index assignment doesn’t, because strings are immutable: ``` >>> S = "spam" >>> S = S[0] + 'l' + S[2:] >>> S 'slam' >>> S = S[0] + 'l' + S[2] + S[3] >>> S 'slam' ``` (See also the Python 3.0 bytearray string type in Chapter 36—it’s a mutable sequence of small integers that is essenti...
Nesting. Here is a sample: ``` >>> me = {'name':('John', 'Q', 'Doe'), 'age':'?', 'job':'engineer'} >>> me['job'] 'engineer' >>> me['name'][2] 'Doe' ``` 11. Files.
Here’s one way to create and read back a text file in Python (ls is a Unix command; use dir on Windows): _# File: maker.py_ ``` file = open('myfile.txt', 'w') file.write('Hello file world!\n') # Or: open().write() file.close() # close not always needed ``` _# File: reader.py_ ``` ...
Coding basic loops. As you work through this exercise, you’ll wind up with code that looks like the following: ``` >>> S = 'spam' >>> for c in S: ...
print(ord(c)) ... 115 112 97 109 >>> x = 0 ``` `>>> for c in S: x += ord(c)` _# Or: x = x + ord(c)_ ``` ... >>> x 433 >>> x = [] >>> for c in S: x.append(ord(c)) ... >>> x [115, 112, 97, 109] ``` `>>> list(map(ord, S))` _# list() required in 3.0, n...
Backslash characters.
The example prints the bell character (\a) 50 times; assuming your machine can handle it, and when it’s run outside of IDLE, you may get a series of beeps (or one sustained tone, if your machine is fast enough).
Hey—I warned you. 3. Sorting dictionaries. Here’s one way to work through this exercise (see Chapter 8 or Chapter 14 if this doesn’t make sense).
Remember, you really do have to split up the keys and sort calls like this because sort returns None.
In Python 2.2 and later, you can iterate through dictionary keys directly without calling keys (e.g., ``` for key in D:), but the keys list will not be sorted like it is by this code.
In more ``` recent Pythons, you can achieve the same effect with the sorted built-in, too: ``` >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7} >>> D {'f': 6, 'c': 3, 'a': 1, 'g': 7, 'e': 5, 'd': 4, 'b': 2} >>> ``` `>>> keys = list(D.keys())` _# list() required in 3.0, not in 2.6_ **|** ...
print(key, '=>', D[key]) ... a => 1 b => 2 c => 3 d => 4 e => 5 f => 6 g => 7 ``` `>>> for key in sorted(D):` _# Better, in more recent Pythons_ ``` ...
print(key, '=>', D[key]) ``` 4. Program logic alternatives. Here’s some sample code for the solutions.
For step e, assign the result of 2 ** X to a variable outside the loops of steps a and b, and use it inside the loop.
Your results may vary a bit; this exercise is mostly designed to get you playing with code alternatives, so anything reasonable gets full credit: _# a_ ``` L = [1, 2, 4, 8, 16, 32, 64] X = 5 i = 0 while i < len(L): if 2 ** X == L[i]: print('at index', i) break i += 1 els...
The basics.
There’s not much to this one, but notice that using print (and hence your function) is technically a polymorphic operation, which does the right thing for each type of object: ``` % python >>> def func(x): print(x) ... >>> func("spam") spam >>> func(42) 42 >>> func([1, 2, 3]) ...
Arguments. Here’s a sample solution.
Remember that you have to use print to see results in the test calls because a file isn’t the same as code typed interactively; Python doesn’t normally echo the results of expression statements in files: **|** ----- ``` def adder(x, y): return x + y print(adder(2, 3)) print(adder('spam', 'eggs')) ...
varargs. Two alternative `adder functions are shown in the following file,` _adders.py.
The hard part here is figuring out how to initialize an accumulator to an_ empty value of whatever type is passed in.
The first solution uses manual type testing to look for an integer, and an empty slice of the first argument (assumed to be a sequence) if the argument is determined not to be an integer.
The second solution uses the first argument to initialize and scan items 2 and beyond, much like one of the min function variants shown in Chapter 18. The second solution is better.
Both of these assume all arguments are of the same type, and neither works on dictionaries (as we saw in Part II, + doesn’t work on mixed types or dictionaries).
You could add a type test and special code to allow dictionaries, too, but that’s extra credit. ``` def adder1(*args): print('adder1', end=' ') if type(args[0]) == type(0): # Integer? sum = 0 # Init to zero else: # else sequence: sum = args[0][...
Keywords. Here is my solution to the first and second parts of this exercise (coded in the file mod.py).
To iterate over keyword arguments, use the **args form in the function header and use a loop (e.g., for x in args.keys(): use args[x]), or use ``` args.values() to make this the same as summing *args positionals: def adder(good=1, bad=2, ugly=3): return good + bad + ugly print(adder()) print(adder(5)...
(and 6.) Here are my solutions to exercises 5 and 6 (file dicts.py).
These are just coding exercises, though, because Python 1.5 added the dictionary methods ``` D.copy() and D1.update(D2) to handle things like copying and adding (merging) ``` dictionaries.
(See Python’s library manual or O’Reilly’s Python Pocket Reference for more details.) X[:] doesn’t work for dictionaries, as they’re not sequences (see Chapter 8 for details).
Also, remember that if you assign (e = d) rather than copying, you generate a reference to a shared dictionary object; changing d changes e, too: ``` def copyDict(old): new = {} for key in old.keys(): new[key] = old[key] return new def addDict(d1, d2): new = {} for key in d...
See #5. 7. More argument-matching examples.
Here is the sort of interaction you should get, along with comments that explain the matching that goes on: ``` 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 ...
Primes revisited. Here is the primes example, wrapped up in a function and a module (file primes.py) so it can be run multiple times. I added an if test to trap negatives, 0, and 1.
I also changed / to // in this edition to make this solution immune to the Python 3.0 / true division changes we studied in Chapter 5, and to enable it to support floating-point numbers (uncomment the `from statement and` change // to / to see the differences in 2.6): ``` #from __future__ import division def pr...
It’s also not a strict mathematical prime (floating points work), and it’s still inefficient. Improvements are left as exercises for more mathematically minded readers.
(Hint: a for loop over range(y, 1, −1) may be a bit quicker than the while, but the algorithm is the real bottleneck here.) To time alternatives, use the built-in time module and coding patterns like those used in this general function-call timer (see the library manual for details): ``` def timer(reps, func, *args...
List comprehensions.
Here is the sort of code you should write; I may have a preference, but I’m not telling: ``` >>> values = [2, 4, 9, 16, 25] >>> import math >>> res = [] >>> for x in values: res.append(math.sqrt(x)) ... >>> res [1.4142135623730951, 2.0, 3.0, 4.0, 5.0] >>> list(map(math.sqrt, values)) ...
Timing tools. Here is some code I wrote to time the three square root options, along with the results in 2.6 and 3.0.
The last result of each function is printed to verify that all three do the same work: _# File mytimer.py (2.6 and 3.0)_ ``` ...same as listed in Chapter 20... ``` _# File timesqrt.py_ **|** **f** ----- ``` import sys, mytimer reps = 10000 repslist = range(reps) # Pull out range list time for 2.6 ...
For both, it looks like the ``` math module is quicker than the ** expression, which is quicker than the pow call; ``` however, you should try this with your code and on your own machine and version of Python.
Also, note that Python 3.0 is nearly twice as slow as 2.6 on this test; 3.1 or later might perform better (time this in the future to see for yourself): ``` c:\misc> c:\python30\python timesqrt.py 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] <timer> ---------------------------------- m...
It appears that the two are ``` roughly the same in this regard under Python 3.0; unlike list comprehensions, though, manual loops are slightly faster than dictionary comprehensions today (though the difference isn’t exactly earth-shattering—at the end we save half a second when making 50 dictionaries of 1,000,000 ite...
Again, rather than taking these results as gospel you should investigate further on your own, on your computer and with your Python: ``` c:\misc> c:\python30\python >>> >>> def dictcomp(I): ...
return {i: i for i in range(I)} ... >>> def dictloop(I): ... new = {} ... for i in range(I): new[i] = i ...
return new ... >>> dictcomp(10) {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} >>> dictloop(10) {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} >>> >>> from mytimer import best, timer ``` `>>> best(dictcomp, 10000)[0]` _# 10,000-item dict_ ``` 0.0013519874732672577 >>> best...
Import basics. This one is simpler than you may think.
When you’re done, your file (mymod.py) and interaction should look similar to the following; remember that Python can read a whole file into a list of line strings, and the `len built-in` returns the lengths of strings and lists: ``` def countLines(name): file = open(name) return len(file.readlines()...
To be more robust, you could read line by line with iterators instead and count as you go: ``` def countLines(name): tot = 0 for line in open(name): tot += 1 return tot def countChars(name): tot = 0 for line in open(name): tot += len(line) return tot ``` On Unix, you...
But note that your script may report fewer characters than Windows does—for portability, Python converts Windows \r\n lineend markers to \n, thereby dropping one byte (character) per line.
To match byte counts with Windows exactly, you have to open in binary mode ('rb'), or add the number of bytes corresponding to the number of lines. **|** ----- Incidentally, to do the “ambitious” part of this exercise (passing in a file object so you only open the file once), you’ll probably need to use the seek me...
We didn’t cover it in the text, but it works just like C’s fseek call (and calls it behind the scenes): seek resets the current position in the file to a passed-in offset.
After a seek, future input/output operations are relative to the new position.
To rewind to the start of a file without closing and reopening it, call ``` file.seek(0); the file read methods all pick up at the current position in the file, ``` so you need to rewind to reread.
Here’s what this tweak would look like: ``` def countLines(file): file.seek(0) # Rewind to start of file return len(file.readlines()) def countChars(file): file.seek(0) # Ditto (rewind if needed) return len(file.read()) def test(name): file = ope...
from/from *. Here’s the from * part; replace * with countChars to do the rest: ``` % python >>> from mymod import * >>> countChars("mymod.py") 291 ``` 3. __main__.
If you code it properly, it works in either mode (program run or module import): ``` def countLines(name): file = open(name) return len(file.readlines()) def countChars(name): return len(open(name).read()) def test(name): # Or pass file object return countLines(name),...
Nested imports.