13.16. Related Modules and Documentation

Python has several classes which extend the existing functionality of the core language which we have described in this chapter. The User* modules are like pre-cooked meals, ready to eat. We mentioned how classes have special methods which, if implemented, can customize classes so that when wrapped around a standard type, they can give instances type-like qualities.

UserList and UserDict, along with the new UserString (introduced in Python 1.6), represent modules that define classes that act as wrappers around list, dictionary, and string objects, respectively. The primary objective of these modules is to provide the desired functionality for you so that you do not have to implement them yourself, and to serve as base classes which are appropriate for subclassing and further customization. Python already provides an abundance of useful built-in types, but the added ability to perform “built-it yourself” typing makes it an even more powerful language.

In Chapter 4, we introduced Python's standard as well as other built-in types. The types module is a great place to learn more about Python's types as well as those which are out of the scope of this text. The types module also defines type objects which can be used to make comparisons. (Such comparisons are popular in Python because it does not support method overloading—this keeps the language simple, yet there are tools that add functionality to a part of the language where it had appeared to be lacking.)

The following piece of code checks to see if the object data is passed into the foo function as an integer or string, and does not allow any other type (raises an exception):

						def foo(data):
    if type(data) == type(0):
        print 'you entered an integer'
    elif type(data) == type(''):
        print 'you entered a string'
    else:
						raise TypeError, 'only integers or strings!'

Although the above code is effective, you may also use attributes of the types module instead for more clarity:

						from types import *
						def foo(data):
    if type(data) == IntType:
        print 'you entered an integer'
    elif type(data) == StringType:
        print 'you entered a string'
    else:
						raise TypeError, 'only integers or strings!'

The last related module is the operator module. This module provides functional versions of most of Python's standard operators. There may be occasions where this type of interface proves more versatile than hard-coding use of the standard operators.

Given below is one example. As you look through the code, imagine the extra lines of code which would have been required if individual operators had been part of the implementation:

>>> from operator import *          # import all operators
>>> vec1 = [12, 24]
>>> vec2 = [2, 3, 4]
>>> opvec = (add, sub, mul, div)    # using +, -, *, /
>>> for eachOp in opvec:            # loop thru operators
…        for i in vec1:
…            for j in vec2:
…               print '%s(%d, %d) = %d' % 
…                    (eachOp.__name__, i, j, eachOp(i, j))
…
add(12, 2) = 14
add(12, 3) = 15
add(12, 4) = 16
add(24, 2) = 26
add(24, 3) = 27
add(24, 4) = 28
sub(12, 2) = 10
sub(12, 3) = 9
sub(12, 4) = 8
sub(24, 2) = 22
sub(24, 3) = 21
sub(24, 4) = 20
mul(12, 2) = 24
mul(12, 3) = 36
mul(12, 4) = 48
mul(24, 2) = 48
mul(24, 3) = 72
mul(24, 4) = 96
div(12, 2) = 6
div(12, 3) = 4
div(12, 4) = 3
div(24, 2) = 12
div(24, 3) = 8
div(24, 4) = 6

The code snippet above defines three vectors, two containing operands and the last representing the set of operations the programmer wants to perform on each pair of available operands. The outermost loop iterates through each operation while the inner pair of loops creates every possible combination of ordered pairs from elements of each operand vector. Finally, the print statement simply applies the current operator with the given arguments.

A list of the modules we described above is given in Table 13.5.

Table 13.5. Class Related Modules
ModuleDescription
UserListprovides a class wrapper around list objects
UserDictprovides a class wrapper around dictionary objects
UserString[a]provides a class wrapper around string objects; also included is a MutableString subclass which provides that kind of functionality, if so desired
typesdefines names for all Python object types as used by the standard Python interpreter
operatorprocesses site-specific modules or packages

[a] new in Python 1.6

There are plenty of class and object-oriented programming related questions in the Python FAQ. In Section 13.5.3, we noted how it was dangerous to track instances by keeping references to them. For more information on this phenomenon, see Python FAQ 4.17. Most of the relevant questions on classes and object-oriented programming are found in Sections 4 and 6 of the FAQ.

The code of Example 13.4 is inspired by the code implemented in Python FAQ 4.48. This FAQ includes a short example of wrapping a file object and modifying the write() method. Our version represents a complete class that can be used like a file object rather than simply passing in an existing (and open) file object. The one caveat to our class is that it applies only to files which use the write() method; therefore, we also refer the reader to Exercise 13–16, where the writelines() method is also implemented.

Finally, we point out again, the Python Library and Language Reference manuals are invaluable sources of related material.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset