Text
stringlengths
1
9.41k
The for statement works by repeatedly indexing a sequence from zero to higher indexes, until an out-of-bounds exception is detected.
Because of that, __getitem__ also turns out to be one way to overload iteration in Python—if this method is defined, ``` for loops call the class’s __getitem__ each time through, with successively higher off ``` sets.
It’s a case of “buy one, get one free”—any built-in or user-defined object that responds to indexing also responds to iteration: ``` >>> class stepper: ... def __getitem__(self, i): ...
return self.data[i] ... ``` **|** ----- `>>> X = stepper()` _# X is a stepper object_ ``` >>> X.data = "Spam" >>> ``` `>>> X[1]` _# Indexing calls __getitem___ ``` 'p' ``` `>>> for item in X:` _# for loops call __getitem___ `...
print(item, end=' ')` _# for indexes items 0..N_ ``` ... S p a m ``` In fact, it’s really a case of “buy one, get a bunch free.” Any class that supports for loops automatically supports all iteration contexts in Python, many of which we’ve seen in earlier chapters (iteration contexts were presented in Chapter 14).
For example, the ``` in membership test, list comprehensions, the map built-in, list and tuple assignments, ``` and type constructors will also call __getitem__ automatically, if it’s defined: `>>> 'p' in X` _# All call __getitem__ too_ ``` True ``` `>>> [c for c in X]` _# List comprehension_ ``` ['S', 'p', 'a',...
Today, all iteration contexts in Python will try the __iter__ method first, before trying __getitem__.
That is, they prefer the iteration protocol we learned about in Chapter 14 to repeatedly indexing an object; only if the object does not support the iteration protocol is indexing attempted instead.
Generally speaking, you should prefer ``` __iter__ too—it supports general iteration contexts better than __getitem__ can. ``` Technically, iteration contexts work by calling the iter built-in function to try to find an __iter__ method, which is expected to return an iterator object.
If it’s provided, Python then repeatedly calls this iterator object’s __next__ method to produce items **|** ----- until a StopIteration exception is raised.
If no such __iter__ method is found, Python falls back on the __getitem__ scheme and repeatedly indexes by offsets as before, until an IndexError exception is raised.
A next built-in function is also available as a convenience for manual iterations: next(I) is the same as I.__next__(). _Version skew note: As described in Chapter 14, if you are using Python_ 2.6, the I.__next__() method just described is named I.next() in your Python, and the `next(I) built-in is present for portabi...
Iteration works the same in 2.6 ``` in all other respects. ###### User-Defined Iterators In the `__iter__ scheme, classes implement user-defined iterators by simply imple-` menting the iteration protocol introduced in Chapters 14 and 20 (refer back to those chapters for more background details on iterators).
For example, the following file, _iters.py, defines a user-defined iterator class that generates squares:_ ``` class Squares: def __init__(self, start, stop): # Save state when created self.value = start - 1 self.stop = stop def __iter__(self): # Get iterator object on iter return s...
print(i, end=' ')` _# Each iteration calls __next___ ``` ... 1 4 9 16 25 ``` Here, the iterator object is simply the instance self, because the __next__ method is part of this class.
In more complex scenarios, the iterator object may be defined as a separate class and object with its own state information to support multiple active iterations over the same data (we’ll see an example of this in a moment).
The end of the iteration is signaled with a Python raise statement (more on raising exceptions in the next part of this book).
Manual iterations work as for built-in types as well: `>>> X = Squares(1, 5)` _# Iterate manually: what loops do_ `>>> I = iter(X)` _# iter calls __iter___ `>>> next(I)` _# next calls __next___ ``` 1 >>> next(I) 4 ``` **|** ----- ``` ...more omitted... >>> next(I) 25 ``` `>>> next(I)` _# Can catch thi...
Because __iter__ objects retain explicitly managed state between ``` next calls, they can be more general than __getitem__. ``` On the other hand, using iterators based on __iter__ can sometimes be more complex and less convenient than using __getitem__.
They are really designed for iteration, not random indexing—in fact, they don’t overload the indexing expression at all: ``` >>> X = Squares(1, 5) >>> X[1] AttributeError: Squares instance has no attribute '__getitem__' ``` The __iter__ scheme is also the implementation for all the other iteration contexts we sa...
However, unlike our prior __getitem__ example, we also need to be aware that a class’s `__iter__ may be designed for a single traversal, not many.
For` example, the Squares class is a one-shot iteration; once you’ve iterated over an instance of that class, it’s empty.
You need to make a new iterator object for each new iteration: ``` >>> X = Squares(1, 5) ``` `>>> [n for n in X]` _# Exhausts items_ ``` [1, 4, 9, 16, 25] ``` `>>> [n for n in X]` _# Now it's empty_ ``` [] ``` `>>> [n for n in Squares(1, 5)]` _# Make a new iterator object_ ``` [1, 4, 9, 16, 25] >>> list(Sq...
for i in range(start, stop+1): ... yield i ** 2 ... ``` `>>> for i in gsquares(1, 5):` _# or: (x ** 2 for x in range(1, 5))_ ``` ...
print(i, end=' ') ... 1 4 9 16 25 ``` Unlike the class, the function automatically saves its state between iterations.
Of course, for this artificial example, you could in fact skip both techniques and simply use a ``` for loop, map, or a list comprehension to build the list all at once.
The best and fastest ``` way to accomplish a task in Python is often also the simplest: **|** ----- ``` >>> [x ** 2 for x in range(1, 6)] [1, 4, 9, 16, 25] ``` However, classes may be better at modeling more complex iterations, especially when they can benefit from state information and inheritance hierarchie...
The next section explores one such use case. ###### Multiple Iterators on One Object Earlier, I mentioned that the iterator object may be defined as a separate class with its own state information to support multiple active iterations over the same data.
Consider what happens when we step across a built-in type like a string: ``` >>> S = 'ace' >>> for x in S: ... for y in S: ...
print(x + y, end=' ') ... aa ac ae ca cc ce ea ec ee ``` Here, the outer loop grabs an iterator from the string by calling iter, and each nested loop does the same to get an independent iterator.
Because each active iterator has its own state information, each loop can maintain its own position in the string, regardless of any other active loops. We saw related examples earlier, in Chapters 14 and 20.
For instance, generator functions and expressions, as well as built-ins like map and zip, proved to be single-iterator objects; by contrast, the range built-in and other built-in types, like lists, support multiple active iterators with independent positions. When we code user-defined iterators with classes, it’s up t...
To achieve the multiple-iterator effect, ``` __iter__ simply needs to define a new stateful object for the iterator, instead of re ``` turning self. The following, for example, defines an iterator class that skips every other item on iterations.
Because the iterator object is created anew for each iteration, it supports multiple active loops: ``` class SkipIterator: def __init__(self, wrapped): self.wrapped = wrapped # Iterator state information self.offset = 0 def __next__(self): if self.offset >= len(self.wrapped): # Te...
Each active loop has its own position in the string because each obtains an independent iterator object that records its own state information: ``` % python skipper.py a c e aa ac ae ca cc ce ea ec ee ``` By contrast, our earlier Squares example supports just one active iteration, unless we call `Squares again i...
Here, there is just one` ``` SkipObject, with multiple iterator objects created from it. ``` As before, we could achieve similar results with built-in tools—for example, slicing with a third bound to skip items: ``` >>> S = 'abcdef' >>> for x in S[::2]: ``` `...
for y in S[::2]:` _# New objects on each iteration_ ``` ... print(x + y, end=' ') ... aa ac ae ca cc ce ea ec ee ``` This isn’t quite the same, though, for two reasons.
First, each slice expression here will physically store the result list all at once in memory; iterators, on the other hand, produce just one value at a time, which can save substantial space for large result lists. Second, slices produce new objects, so we’re not really iterating over the same object in multiple place...
To be closer to the class, we would need to make a single object to step across by slicing ahead of time: ``` >>> S = 'abcdef' >>> S = S[::2] >>> S 'ace' >>> for x in S: ``` `...
for y in S:` _# Same object, new iterators_ ``` ...
print(x + y, end=' ') ... aa ac ae ca cc ce ea ec ee ``` **|** ----- This is more similar to our class-based solution, but it still stores the slice result in memory all at once (there is no generator form of built-in slicing today), and it’s only equivalent for this particular case of skipping every other item...
Regardless of whether our applications require such generality, user-defined iterators are a powerful tool—they allow us to make arbitrary objects look and feel like the other sequences and iterables we have met in this book.
We could use this technique with a database object, for example, to support iterations over database fetches, with multiple cursors into the same query result. ###### Membership: __contains__, __iter__, and __getitem__ The iteration story is even richer than we’ve seen thus far.
Operator overloading is often _layered: classes may provide specific methods, or more general alternatives used as_ fallback options.
For example: - Comparisons in Python 2.6 use specific methods such as __lt__ for less than if present, or else the general __cmp__.
Python 3.0 uses only specific methods, not ``` __cmp__, as discussed later in this chapter. ``` - Boolean tests similarly try a specific __bool__ first (to give an explicit True/False result), and if it’s absent fall back on the more general __len__ (a nonzero length means True).
As we’ll also see later in this chapter, Python 2.6 works the same but uses the name __nonzero__ instead of __bool__. In the iterations domain, classes normally implement the in membership operator as an iteration, using either the __iter__ method or the __getitem__ method.
To support more specific membership, though, classes may code a __contains__ method—when present, this method is preferred over __iter__, which is preferred over __getitem__. The __contains__ method should define membership as applying to keys for a map_ping (and can use quick lookups), and as a search for sequences._ ...
Its methods print trace messages when called: ``` class Iters: def __init__(self, value): self.data = value def __getitem__(self, i): # Fallback for iteration print('get[%s]:' % i, end='') # Also for index, slice return self.data[i] def __iter__(self): # Preferred ...
Slice expressions trigger __getitem__ with a slice object containing bounds, both for built-in types and user-defined classes, so slicing is automatic in our class: `>>> X = Iters('spam')` _# Indexing_ `>>> X[0]` _# __getitem__(0)_ ``` get[0]:'s' ``` `>>> 'spam'[1:]` _# Slice syntax_ ``` 'pam' ``` `>>> 'spam'[sl...
More specifically, it’s` called with the attribute name as a string whenever you try to qualify an instance with an undefined (nonexistent) attribute name.
It is not called if Python can find the attribute using its inheritance tree search procedure.
Because of its behavior, __getattr__ is useful as a hook for responding to attribute requests in a generic fashion. For example: ``` >>> class empty: ... def __getattr__(self, attrname): ...
if attrname == "age": ... return 40 ... else: ...
raise AttributeError, attrname ... >>> X = empty() >>> X.age 40 >>> X.name ...error text omitted... AttributeError: name ``` Here, the empty class and its instance X have no real attributes of their own, so the access to X.age gets routed to the __getattr__ method; self is assigned the instance (X), and ...
The class makes age ``` look like a real attribute by returning a real value as the result of the X.age qualification expression (40).
In effect, age becomes a dynamically computed attribute. **|** ----- For attributes that the class doesn’t know how to handle, __getattr__ raises the builtin AttributeError exception to tell Python that these are bona fide undefined names; asking for X.name triggers the error.
You’ll see __getattr__ again when we see delegation and properties at work in the next two chapters, and I’ll say more about exceptions in Part VII. A related overloading method, __setattr__, intercepts all attribute assignments.
If this method is defined, self.attr = `value becomes self.__setattr__('attr',` `value).
This` is a bit trickier to use because assigning to any self attributes within __setattr__ calls ``` __setattr__ again, causing an infinite recursion loop (and eventually, a stack overflow ``` exception!).
If you want to use this method, be sure that it assigns any instance attributes by indexing the attribute dictionary, discussed in the next section.
That is, use ``` self.__dict__['name'] = x, not self.name = x: >>> class accesscontrol: ... def __setattr__(self, attr, value): ... if attr == 'age': ... self.__dict__[attr] = value ...
else: ...
raise AttributeError, attr + ' not allowed' ... >>> X = accesscontrol() ``` `>>> X.age = 40` _# Calls __setattr___ ``` >>> X.age 40 >>> X.name = 'mel' ...text omitted... AttributeError: name not allowed ``` These two attribute-access overloading methods allow you to control or specialize access to attri...
They tend to play highly specialized roles, some of which we’ll explore later in this book. ###### Other Attribute Management Tools For future reference, also note that there are other ways to manage attribute access in Python: - The __getattribute__ method intercepts all attribute fetches, not just those that are ...
Although Python doesn’t support private declarations per se, techniques like this can emulate much of their purpose.
This is a partial solution, though; to make it more effective, it must be augmented to allow subclasses to set private attributes more naturally, too, and to use ``` __getattr__ and a wrapper (sometimes called a proxy) class to check for private at ``` tribute fetches. We’ll postpone a more complete solution to attrib...
Even_ though privacy can be emulated this way, though, it almost never is in practice.
Python programmers are able to write large OOP frameworks and applications without private declarations—an interesting finding about access controls in general that is beyond the scope of our purposes here. Catching attribute references and assignments is generally a useful technique; it supports delegation, a design ...
String formatting is used to convert the managed ``` self.data object to a string.
If defined, __repr__ (or its sibling, __str__) is called auto ``` matically when class instances are printed or converted to strings.
These methods allow you to define a better display format for your objects than the default instance display. The default display of instance objects is neither useful nor pretty: ``` >>> class adder: ...
def __init__(self, value=0): ``` `... self.data = value` _# Initialize data_ ``` ... def __add__(self, other): ``` `...
self.data += other` _# Add other in-place (bad!)_ ``` ... ``` `>>> x = adder()` _# Default displays_ ``` >>> print(x) <__main__.adder object at 0x025D66B0> >>> x <__main__.adder object at 0x025D66B0> ``` But coding or inheriting string representation methods allows us to customize the display: `>>> class a...
def __repr__(self):` _# Add string representation_ `...
return 'addrepr(%s)' % self.data` _# Convert to as-code string_ ``` ... ``` `>>> x = addrepr(2)` _# Runs __init___ `>>> x + 1` _# Runs __add___ `>>> x` _# Runs __repr___ ``` addrepr(3) ``` `>>> print(x)` _# Runs __repr___ ``` addrepr(3) ``` `>>> str(x), repr(x)` _# Runs __repr__ for both_ ``` ('addrepr(3)', ...
Mostly, to support different audiences. In full detail: - __str__ is tried first for the print operation and the str built-in function (the internal equivalent of which print runs).
It generally should return a user-friendly display. - __repr__ is used in all other contexts: for interactive echoes, the repr function, and nested appearances, as well as by print and str if no __str__ is present.
It should generally return an as-code string that could be used to re-create the object, or a detailed display for developers. In a nutshell, __repr__ is used everywhere, except by print and str when a __str__ is defined.
Note, however, that while printing falls back on `__repr__ if no` `__str__ is` **|** ----- defined, the inverse is not true—other contexts, such as interactive echoes, use ``` __repr__ only and don’t try __str__ at all: >>> class addstr(adder): ``` `...
def __str__(self):` _# __str__ but no __repr___ `...
return '[Value: %s]' % self.data` _# Convert to nice string_ ``` ... >>> x = addstr(3) >>> x + 1 ``` `>>> x` _# Default __repr___ ``` <__main__.addstr object at 0x00B35EF0> ``` `>>> print(x)` _# Runs __str___ ``` [Value: 4] >>> str(x), repr(x) ('[Value: 4]', '<__main__.addstr object at 0x00B35EF0>') ``...
By defining both methods, though, you can support different displays in different contexts—for example, an end-user display with __str__, and a low-level display for programmers to use during development with __repr__.
In effect, __str__ simply overrides __repr__ for user-friendly display contexts: ``` >>> class addboth(adder): ... def __str__(self): ``` `...
return '[Value: %s]' % self.data` _# User-friendly string_ ``` ... def __repr__(self): ``` `...
return 'addboth(%s)' % self.data` _# As-code string_ ``` ... >>> x = addboth(4) >>> x + 1 ``` `>>> x` _# Runs __repr___ ``` addboth(5) ``` `>>> print(x)` _# Runs __str___ ``` [Value: 5] >>> str(x), repr(x) ('[Value: 5]', 'addboth(5)') ``` I should mention two usage notes here.
First, keep in mind that `__str__ and` ``` __repr__ must both return strings; other result types are not converted and raise errors, ``` so be sure to run them through a converter if needed.
Second, depending on a container’s string-conversion logic, the user-friendly display of __str__ might only apply when objects appear at the top level of a print operation; objects nested in larger objects might still print with their __repr__ or its default.
The following illustrates both of these points: ``` >>> class Printer: ... def __init__(self, val): ... self.val = val ``` `... def __str__(self):` _# Used for instance itself_ `...
return str(self.val)` _# Convert to a string result_ ``` ... >>> objs = [Printer(2), Printer(3)] ``` `>>> for x in objs: print(x)` _# __str__ run when instance printed_ ``` ...
# But not when instance in a list! ``` **|** ----- ``` 2 3 >>> print(objs) [<__main__.Printer object at 0x025D06F0>, <__main__.Printer object at ...more... >>> objs [<__main__.Printer object at 0x025D06F0>, <__main__.Printer object at ...more... ``` To ensure that a custom display is run in all context...
def __init__(self, val): ... self.val = val ``` `... def __repr__(self):` _# __repr__ used by print if no __str___ `...
return str(self.val)` _# __repr__ used if echoed or nested_ ``` ... >>> objs = [Printer(2), Printer(3)] ``` `>>> for x in objs: print(x)` _# No __str__: runs __repr___ ``` ... 2 3 ``` `>>> print(objs)` _# Runs __repr__, not ___str___ ``` [2, 3] >>> objs [2, 3] ``` In practice, __str__ (or its low-lev...
Any time you can print an object and see a custom display, one of these two tools is probably in use. ###### Right-Side and In-Place Addition: __radd__ and __iadd__ Technically, the __add__ method that appeared in the prior example does not support the use of instance objects on the right side of the `+ operator.
To implement such` expressions, and hence support _commutative-style operators, code the_ `__radd__` method as well.
Python calls __radd__ only when the object on the right side of the + is your class instance, but the object on the left is not an instance of your class.
The ``` __add__ method for the object on the left is called instead in all other cases: >>> class Commuter: ... def __init__(self, val): ... self.val = val ... def __add__(self, other): ...
print('add', self.val, other) ... return self.val + other ... def __radd__(self, other): ... print('radd', self.val, other) ...
return other + self.val ... >>> x = Commuter(88) >>> y = Commuter(99) ``` **|** ----- `>>> x + 1` _# __add__: instance + noninstance_ ``` add 88 1 89 ``` `>>> 1 + y` _# __radd__: noninstance + instance_ ``` radd 99 1 100 ``` `>>> x + y` _# __add__: instance + instance, triggers __radd___ ``` add 8...
Also note that x and y are instances of the same class here; when ``` instances of different classes appear mixed in an expression, Python prefers the class of the one on the left.