3.3.4 Emulating sequence and mapping types

The following methods can be defined to emulate sequence or mapping objects. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which 0 <= k < N where N is the length of the sequence, and the method __getslice__() (see below) should be defined. It is also recommended that mappings provide methods keys(), values(), items(), has_key(), get(), clear(), copy(), and update() behaving similar to those for Python's standard dictionary objects; mutable sequences should provide methods append(), count(), index(), insert(), pop(), remove(), reverse() and sort(), like Python standard list objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods __add__(), __radd__(), __mul__() and __rmul__() described below; they should not define __coerce__() or other numerical operators.

__len__ (self)
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

__getitem__ (self, key)
Called to implement evaluation of self[key]. For a sequence types, the accepted keys should be integers. Note that the special interpretation of negative indices (if the class wishes to emulate a sequence type) is up to the __getitem__() method.

__setitem__ (self, key, value)
Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced.

__delitem__ (self, key)
Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence.


Send comments on this document to python-docs@python.org.