1. docs.Python.org2. Python Source Code3. Data model3.1. Objects, values and types?Objects are Python’s abstraction for data. All data in a Python programis represented by objects or by relations between objects. (In a sense, and inconformance to Von Neumann’s model of a “stored program computer,” code is alsorepresented by objects.)Every object has an identity, a type and a value. An object’s identity neverchanges once it has been created; you may think of it as the object’s address inmemory.The ‘is‘ operator compares the identity of two objects:the id() function returns an integer representing its identity (currentlyimplemented as its address).An object’s type is also unchangeable. [1] An object’s type determines the operations that the object supports (e.g., “doesit have a length?”) and also defines the possible values for objects of thattype. The type() function returns an object’s type (which is an objectitself). The value of some objects can change. Objects whose value canchange are said to be mutable; objects whose value is unchangeable once theyare created are called immutable. (The value of an immutable container objectthat contains a reference to a mutable object can change when the latter’s valueis changed; however the container is still considered immutable, because thecollection of objects it contains cannot be changed. So, immutability is notstrictly the same as having an unchangeable value, it is more subtle.) Anobject’s mutability is determined by its type; for instance, numbers, stringsand tuples are immutable, while dictionaries and lists are mutable.Objects are never explicitly destroyed; however, when they become unreachablethey may be garbage-collected. An implementation is allowed to postpone garbagecollection or omit it altogether — it is a matter of implementation qualityhow garbage collection is implemented, as long as no objects are collected thatare still reachable.CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayeddetection of cyclically linked garbage, which collects most objects as soonas they become unreachable, but is not guaranteed to collect garbagecontaining circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage.Other implementations act differently and CPython may change.Note that the use of the implementation’s tracing or debugging facilities maykeep objects alive that would normally be collectable. Also note that catchingan exception with a ‘try...except‘ statement may keepobjects alive.Some objects contain references to “external” resources such as open files orwindows. It is understood that these resources are freed when the object isgarbage-collected, but since garbage collection is not guaranteed to happen,such objects also provide an explicit way to release the external resource,usually a close() method. Programs are strongly recommended to explicitlyclose such objects. The ‘try...finally‘ statementprovides a convenient way to do this.Some objects contain references to other objects; these are called containers.Examples of containers are tuples, lists and dictionaries. The references arepart of a container’s value. In most cases, when we talk about the value of acontainer, we imply the values, not the identities of the contained objects;v  however, when we talk about the mutability of a container, only the identitiesof the immediately contained objects are implied. So, if an immutable container(like a tuple) contains a reference to a mutable object, its value changes ifthat mutable object is changed.Types affect almost all aspects of object behavior. Even the importance ofobject identity is affected in some sense: for immutable types, operations thatcompute new values may actually return a reference to any existing object withthe same type and value, while for mutable objects this is not allowed. E.g.,after a = 1; b = 1, a and b may or may not refer to the same objectwith the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newlycreated empty lists. (Note that c = d = [] assigns the same object to both c and d.)3.2. The standard type hierarchy?Below is a list of the types that are built into Python. Extension modules(written in C, Java, or other languages, depending on the implementation) candefine additional types. Future versions of Python may add types to the typehierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).Some of the type descriptions below contain a paragraph listing ‘specialattributes.’ These are attributes that provide access to the implementation andare not intended for general use. Their definition may change in the future.NoneThis type has a single value. There is a single object with this value. Thisobject is accessed through the built-in name None. It is used to signify theabsence of a value in many situations, e.g., it is returned from functions thatdon’t explicitly return anything. Its truth value is false.NotImplementedThis type has a single value. There is a single object with this value. Thisobject is accessed through the built-in name NotImplemented. Numeric methodsand rich comparison methods may return this value if they do not implement theoperation for the operands provided. (The interpreter will then try thereflected operation, or some other fallback, depending on the operator.) Itstruth value is true.EllipsisThis type has a single value. There is a single object with this value. Thisobject is accessed through the built-in name Ellipsis. It is used toindicate the presence of the ... syntax in a slice. Its truth value istrue.numbers.NumberThese are created by numeric literals and returned as results by arithmeticoperators and arithmetic built-in functions. Numeric objects are immutable;once created their value never changes. Python numbers are of course stronglyrelated to mathematical numbers, but subject to the limitations of numericalrepresentation in computers.Python distinguishes between integers, floating point numbers, and complexnumbers:numbers.IntegralThese represent elements from the mathematical set of integers (positive andnegative).There are three types of integers:Plain integersThese represent numbers in the range -2147483648 through 2147483647.(The range may be larger on machines with a larger natural word size,but not smaller.) When the result of an operation would fall outsidethis range, the result is normally returned as a long integer (in somecases, the exception OverflowError is raised instead). For thepurpose of shift and mask operations, integers are assumed to have abinary, 2’s complement notation using 32 or more bits, and hiding nobits from the user (i.e., all 4294967296 different bit patternscorrespond to different values).Long integersThese represent numbers in an unlimited range, subject to available(virtual) memory only. For the purpose of shift and mask operations, abinary representation is assumed, and negative numbers are representedin a variant of 2’s complement which gives the illusion of an infinitestring of sign bits extending to the left.BooleansThese represent the truth values False and True. The two objectsrepresenting the values False and True are the only Boolean objects.The Boolean type is a subtype of plain integers, and Boolean valuesbehave like the values 0 and 1, respectively, in almost all contexts,the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.The rules for integer representation are intended to give the mostmeaningful interpretation of shift and mask operations involving negativeintegers and the least surprises when switching between the plain and longinteger domains. Any operation, if it yields a result in the plaininteger domain, will yield the same result in the long integer domain orwhen using mixed operands. The switch between domains is transparent tothe programmer.numbers.Real (float)These represent machine-level double precision floating point numbers. You areat the mercy of the underlying machine architecture (and C or Javaimplementation) for the accepted range and handling of overflow. Python does notsupport single-precision floating point numbers; the savings in processor andmemory usage that are usually the reason for using these is dwarfed by theoverhead of using objects in Python, so there is no reason to complicate thelanguage with two kinds of floating point numbers.numbers.ComplexThese represent complex numbers as a pair of machine-level double precisionfloating point numbers. The same caveats apply as for floating point numbers.The real and imaginary parts of a complex number z can be retrieved throughthe read-only attributes z.real and z.imag.SequencesThese represent finite ordered sets indexed by non-negative numbers. Thebuilt-in function len() returns the number of items of a sequence. Whenthe length of a sequence is n, the index set contains the numbers 0, 1,..., n-1. Item i of sequence a is selected by a[i].Sequences also support slicing: a[i:j] selects all items with index k suchthat i k j. When used as an expression, a slice is asequence of the same type. This implies that the index set is renumbered sothat it starts at 0.Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i x j.Sequences are distinguished according to their mutability:Immutable sequencesAn object of an immutable sequence type cannot change once it is created. (Ifthe object contains references to other objects, these other objects may bemutable and may be changed; however, the collection of objects directlyreferenced by an immutable object cannot change.)The following types are immutable sequences:StringsThe items of a string are characters. There is no separate character type; acharacter is represented by a string of one item. Characters represent (atleast) 8-bit bytes. The built-in functions chr() and ord() convertbetween characters and nonnegative integers representing the byte values. Byteswith the values 0-127 usually represent the corresponding ASCII values, but theinterpretation of values is up to the program. The string data type is alsoused to represent arrays of bytes, e.g., to hold data read from a file.(On systems whose native character set is not ASCII, strings may use EBCDIC intheir internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparisonpreserves the ASCII order. Or perhaps someone can propose a better rule?)UnicodeThe items of a Unicode object are Unicode code units. A Unicode code unit isrepresented by a Unicode object of one item and can hold either a 16-bit or32-bit value representing a Unicode ordinal (the maximum value for the ordinalis given in sys.maxunicode, and depends on how Python is configured atcompile time). Surrogate pairs may be present in the Unicode object, and willbe reported as two separate items. The built-in functions unichr() and ord() convert between code units and nonnegative integers representing theUnicode ordinals as defined in the Unicode Standard 3.0. Conversion from and toother encodings are possible through the Unicode method encode() and thebuilt-in function unicode().TuplesThe items of a tuple are arbitrary Python objects. Tuples of two or more itemsare formed by comma-separated lists of expressions. A tuple of one item (a‘singleton’) can be formed by affixing a comma to an expression (an expressionby itself does not create a tuple, since parentheses must be usable for groupingof expressions). An empty tuple can be formed by an empty pair of parentheses.Mutable sequencesMutable sequences can be changed after they are created. The subscription andslicing notations can be used as the target of assignment and del (delete) statements.There are currently two intrinsic mutable sequence types:ListsThe items of a list are arbitrary Python objects. Lists are formed by placing acomma-separated list of expressions in square brackets. (Note that there are nospecial cases needed to form lists of length 0 or 1.)Byte ArraysA bytearray object is a mutable array. They are created by the built-in bytearray() constructor. Aside from being mutable (and henceunhashable), byte arrays otherwise provide the same interface andfunctionality as immutable bytes objects.The extension module array provides an additional example of a mutablesequence type.Set typesThese represent unordered, finite sets of unique, immutable objects. As such,they cannot be indexed by any subscript. However, they can be iterated over, andthe built-in function len() returns the number of items in a set. Commonuses for sets are fast membership testing, removing duplicates from a sequence,and computing mathematical operations such as intersection, union, difference,and symmetric difference.For set elements, the same immutability rules apply as for dictionary keys. Notethat numeric types obey the normal rules for numeric comparison: if two numberscompare equal (e.g., 1 and 1.0), only one of them can be contained in aset.There are currently two intrinsic set types:SetsThese represent a mutable set. They are created by the built-in set() constructor and can be modified afterwards by several methods, such as add().Frozen setsThese represent an immutable set. They are created by the built-in frozenset() constructor. As a frozenset is immutable and hashable, it can be used again as an element of another set, or asa dictionary key.MappingsThese represent finite sets of objects indexed by arbitrary index sets. Thesubscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len() returns the numberof items in a mapping.There is currently a single intrinsic mapping type:DictionariesThese represent finite sets of objects indexed by nearly arbitrary values. Theonly types of values not acceptable as keys are values containing lists ordictionaries or other mutable types that are compared by value rather than byobject identity, the reason being that the efficient implementation ofdictionaries requires a key’s hash value to remain constant. Numeric types usedfor keys obey the normal rules for numeric comparison: if two numbers compareequal (e.g., 1 and 1.0) then they can be used interchangeably to indexthe same dictionary entry.Dictionaries are mutable; they can be created by the {...} notation (seesection Dictionary displays).The extension modules dbm, gdbm, and bsddb provideadditional examples of mapping types.Callable typesThese are the types to which the function call operation (see section Calls) can be applied:User-defined functionsA user-defined function object is created by a function definition (seesection Function definitions). It should be called with an argument listcontaining the same number of items as the function’s formal parameterlist.Special attributes:AttributeMeaning func_docThe function’s documentationstring, or None ifunavailableWritable__doc__Another way of spelling func_docWritablefunc_nameThe function’s nameWritable__name__Another way of spelling func_nameWritable__module__The name of the module thefunction was defined in, or None if unavailable.Writablefunc_defaultsA tuple containing defaultargument values for thosearguments that have defaults,or None if no argumentshave a default valueWritablefunc_codeThe code object representingthe compiled function body.Writablefunc_globalsA reference to the dictionarythat holds the function’sglobal variables — theglobal namespace of themodule in which the functionwas defined.Read-onlyfunc_dictThe namespace supportingarbitrary functionattributes.Writablefunc_closureNone or a tuple of cellsthat contain bindings for thefunction’s free variables.Read-onlyMost of the attributes labelled “Writable” check the type of the assigned value.Changed in version 2.4: func_name is now writable.Function objects also support getting and setting arbitrary attributes, whichcan be used, for example, to attach metadata to functions. Regular attributedot-notation is used to get and set such attributes. Note that the currentimplementation only supports function attributes on user-defined functions.Function attributes on built-in functions may be supported in the future.Additional information about a function’s definition can be retrieved from itscode object; see the description of internal types below.User-defined methodsA user-defined method object combines a class, a class instance (or None)and any callable object (normally a user-defined function).Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method forunbound methods; __doc__ is the method’s documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the methodwas defined in, or None if unavailable.Changed in version 2.2: im_self used to refer to the class that defined the method.Changed in version 2.6: For 3.0 forward-compatibility, im_func is also available as __func__, and im_self as __self__.Methods also support accessing (but not setting) the arbitrary functionattributes on the underlying function object.User-defined method objects may be created when getting an attribute of a class(perhaps via an instance of that class), if that attribute is a user-definedfunction object, an unbound user-defined method object, or a class methodobject. When the attribute is a user-defined method object, a new method objectis only created if the class from which it is being retrieved is the same as, ora derived class of, the class stored in the original method object; otherwise,the original method object is used as it is.When a user-defined method object is created by retrieving a user-definedfunction object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created byretrieving a user-defined function object from a class via one of itsinstances, its im_self attribute is the instance, and the methodobject is said to be bound. In either case, the new method’s im_class attribute is the class from which the retrieval takesplace, and its im_func attribute is the original function object.When a user-defined method object is created by retrieving another method objectfrom a class or instance, the behaviour is the same as for a function object,except that the im_func attribute of the new instance is not theoriginal method object but its im_func attribute.When a user-defined method object is created by retrieving a class method objectfrom a class or instance, its im_self attribute is the class itself (thesame as the im_class attribute), and its im_func attribute isthe function object underlying the class method.When an unbound user-defined method object is called, the underlying function(im_func) is called, with the restriction that the first argument mustbe an instance of the proper class (im_class) or of a derived classthereof.When a bound user-defined method object is called, the underlying function(im_func) is called, inserting the class instance (im_self) infront of the argument list. For instance, when C is a class whichcontains a definition for a function f(), and x is an instance of C, calling x.f(1) is equivalent to calling C.f(x, 1).When a user-defined method object is derived from a class method object, the“class instance” stored in im_self will actually be the class itself, sothat calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.Note that the transformation from function object to (unbound or bound) methodobject happens each time the attribute is retrieved from the class or instance.In some cases, a fruitful optimization is to assign the attribute to a localvariable and call that local variable. Also notice that this transformation onlyhappens for user-defined functions; other callable objects (and all non-callableobjects) are retrieved without transformation. It is also important to notethat user-defined functions which are attributes of a class instance are notconverted to bound methods; this only happens when the function is anattribute of the class.Generator functionsA function or method which uses the yield statement (see section The yield statement) is called a generatorfunction. Such a function, when called, always returns an iterator objectwhich can be used to execute the body of the function: calling the iterator’s next() method will cause the function to execute until it provides a valueusing the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set ofvalues to be returned.Built-in functionsA built-in function object is a wrapper around a C function. Examples ofbuilt-in functions are len() and math.sin() (math is astandard built-in module). The number and type of the arguments aredetermined by the C function. Special read-only attributes: __doc__ is the function’s documentation string, or None ifunavailable; __name__ is the function’s name; __self__ isset to None (but see the next item); __module__ is the name ofthe module the function was defined in or None if unavailable.Built-in methodsThis is really a different disguise of a built-in function, this time containingan object passed to the C function as an implicit extra argument. An example ofa built-in method is alist.append(), assuming alist is a list object. Inthis case, the special read-only attribute __self__ is set to the objectdenoted by list.Class TypesClass types, or “new-style classes,” are callable. These objects normally actas factories for new instances of themselves, but variations are possible forclass types that override __new__(). The arguments of the call are passedto __new__() and, in the typical case, to __init__() to initializethe new instance.Classic ClassesClass objects are described below. When a class object is called, a new classinstance (also described below) is created and returned. This implies a call tothe class’s __init__() method if it has one. Any arguments are passed onto the __init__() method. If there is no __init__() method, theclass must be called without arguments.Class instancesClass instances are described below. Class instances are callable only when theclass has a __call__() method; x(arguments) is a shorthand for x.__call__(arguments).ModulesModules are imported by the import statement (see section The import statement). A module object has a namespace implemented by a dictionary object (this is the dictionary referencedby the func_globals attribute of functions defined in the module). Attributereferences are translated to lookups in this dictionary, e.g., m.x isequivalent to m.__dict__["x"]. A module object does not contain the codeobject used to initialize the module (since it isn’t needed once theinitialization is done).Attribute assignment updates the module’s namespace dictionary, e.g., m.x = 1 is equivalent to m.__dict__["x"] = 1.Special read-only attribute: __dict__ is the module’s namespace as adictionary object.Predefined (writable) attributes: __name__ is the module’s name; __doc__ is the module’s documentation string, or None ifunavailable; __file__ is the pathname of the file from which the modulewas loaded, if it was loaded from a file. The __file__ attribute is notpresent for C modules that are statically linked into the interpreter; forextension modules loaded dynamically from a shared library, it is the pathnameof the shared library file.ClassesBoth class types (new-style classes) and class objects (old-style/classicclasses) are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object.Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although for new-style classesin particular there are a number of hooks which allow for other means oflocating attributes). When the attribute name is not found there, theattribute search continues in the base classes. For old-style classes, thesearch is depth-first, left-to-right in the order of occurrence in the baseclass list. New-style classes use the more complex C3 method resolutionorder which behaves correctly even in the presence of ‘diamond’inheritance structures where there are multiple inheritance pathsleading back to a common ancestor. Additional details on the C3 MRO used bynew-style classes can be found in the documentation accompanying the2.3 release at http://www.python.org/download/releases/2.3/mro/.When a class attribute reference (for class C, say) would yield auser-defined function object or an unbound user-defined method object whoseassociated class is either C or one of its base classes, it istransformed into an unbound user-defined method object whose im_class attribute is C. When it would yield a class method object, it istransformed into a bound user-defined method object whose im_class and im_self attributes are both C. When it would yield astatic method object, it is transformed into the object wrapped by the staticmethod object. See section Implementing Descriptors for another way in whichattributes retrieved from a class may differ from those actually contained inits __dict__ (note that only new-style classes support descriptors).Class attribute assignments update the class’s dictionary, never the dictionaryof a base class.A class object can be called (see above) to yield a class instance (see below).Special attributes: __name__ is the class name; __module__ isthe module name in which the class was defined; __dict__ is thedictionary containing the class’s namespace; __bases__ is a tuple(possibly empty or a singleton) containing the base classes, in the order oftheir occurrence in the base class list; __doc__ is the class’sdocumentation string, or None if undefined.Class instancesA class instance is created by calling a class object (see above). A classinstance has a namespace implemented as a dictionary which is the first place inwhich attribute references are searched. When an attribute is not found there,and the instance’s class has an attribute by that name, the search continueswith the class attributes. If a class attribute is found that is a user-definedfunction object or an unbound user-defined method object whose associated classis the class (call it C) of the instance for which the attributereference was initiated or one of its bases, it is transformed into a bounduser-defined method object whose im_class attribute is C andwhose im_self attribute is the instance. Static method and class methodobjects are also transformed, as if they had been retrieved from class C; see above under “Classes”. See section Implementing Descriptors foranother way in which attributes of a class retrieved via its instances maydiffer from the objects actually stored in the class’s __dict__. If noclass attribute is found, and the object’s class has a __getattr__() method, that is called to satisfy the lookup.Attribute assignments and deletions update the instance’s dictionary, never aclass’s dictionary. If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instancedictionary directly.Class instances can pretend to be numbers, sequences, or mappings if they havemethods with certain special names. See section Special method names.Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class.FilesA file object represents an open file. File objects are created by the open() built-in function, and also by os.popen(), os.fdopen(), and the makefile() method of socket objects (andperhaps by other functions or methods provided by extension modules). Theobjects sys.stdin, sys.stdout and sys.stderr are initialized tofile objects corresponding to the interpreter’s standard input, output anderror streams. See File Objects for complete documentation offile objects.Internal typesA few types used internally by the interpreter are exposed to the user. Theirdefinitions may change with future versions of the interpreter, but they arementioned here for completeness.Code objectsCode objects represent byte-compiled executable Python code, or bytecode.The difference between a code object and a function object is that the functionobject contains an explicit reference to the function’s globals (the module inwhich it was defined), while a code object contains no context; also the defaultargument values are stored in the function object, not in the code object(because they represent values calculated at run-time). Unlike functionobjects, code objects are immutable and contain no references (directly orindirectly) to mutable objects.Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including argumentswith default values); co_nlocals is the number of local variables usedby the function (including arguments); co_varnames is a tuple containingthe names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that arereferenced by nested functions; co_freevars is a tuple containing thenames of free variables; co_code is a string representing the sequenceof bytecode instructions; co_consts is a tuple containing the literalsused by the bytecode; co_names is a tuple containing the names used bythe bytecode; co_filename is the filename from which the code wascompiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets toline numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.The following flag bits are defined for co_flags: bit 0x04 is set ifthe function uses the *arguments syntax to accept an arbitrary number ofpositional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments; bit 0x20 is setif the function is a generator.Future feature declarations (from __future__ import division) also use bitsin co_flags to indicate whether a code object was compiled with aparticular feature enabled: bit 0x2000 is set if the function was compiledwith future division enabled; bits 0x10 and 0x1000 were used in earlierversions of Python.Other bits in co_flags are reserved for internal use.If a code object represents a function, the first item in co_consts isthe documentation string of the function, or None if undefined.Frame objectsFrame objects represent execution frames. They may occur in traceback objects(see below).Special read-only attributes: f_back is to the previous stack frame(towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used forglobal variables; f_builtins is used for built-in (intrinsic) names; f_restricted is a flag indicating whether the function is executing inrestricted execution mode; f_lasti gives the precise instruction (thisis an index into the bytecode string of the code object).Special writable attributes: f_trace, if not None, is a functioncalled at the start of each source code line (this is used by the debugger); f_exc_type, f_exc_value, f_exc_traceback represent thelast exception raised in the parent frame provided another exception was everraised in the current frame (in all other cases they are None); f_lineno is the current line number of the frame — writing to this from within a tracefunction jumps to the given line (only for the bottom-most frame). A debuggercan implement a Jump command (aka Set Next Statement) by writing to f_lineno.Traceback objectsTraceback objects represent a stack trace of an exception. A traceback objectis created when an exception occurs. When the search for an exception handlerunwinds the execution stack, at each unwound level a traceback object isinserted in front of the current traceback. When an exception handler isentered, the stack trace is made available to the program. (See section The try statement.) It is accessible as sys.exc_traceback,and also as the third item of the tuple returned by sys.exc_info(). Thelatter is the preferred interface, since it works correctly when the program isusing multiple threads. When the program contains no suitable handler, the stacktrace is written (nicely formatted) to the standard error stream; if theinterpreter is interactive, it is also made available to the user as sys.last_traceback.Special read-only attributes: tb_next is the next level in the stacktrace (towards the frame where the exception occurred), or None if there isno next level; tb_frame points to the execution frame of the currentlevel; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and lastinstruction in the traceback may differ from the line number of its frame objectif the exception occurred in a try statement with no matching exceptclause or with a finally clause.Slice objectsSlice objects are used to represent slices when extended slice syntax is used.This is a slice using two colons, or multiple slices or ellipses separated bycommas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They arealso created by the built-in slice() function.Special read-only attributes: start is the lower bound; stop isthe upper bound; step is the step value; each is None if omitted.These attributes can have any type.Slice objects support one method:slice.indices(self, length)?This method takes a single integer argument length and computes informationabout the extended slice that the slice object would describe if applied to asequence of length items. It returns a tuple of three integers; respectivelythese are the start and stop indices and the step or stride length of theslice. Missing or out-of-bounds indices are handled in a manner consistent withregular slices.New in version 2.3.Static method objectsStatic method objects provide a way of defeating the transformation of functionobjects to method objects described above. A static method object is a wrapperaround any other object, usually a user-defined method object. When a staticmethod object is retrieved from a class or a class instance, the object actuallyreturned is the wrapped object, which is not subject to any furthertransformation. Static method objects are not themselves callable, although theobjects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor.Class method objectsA class method object, like a static method object, is a wrapper around anotherobject that alters the way in which that object is retrieved from classes andclass instances. The behaviour of class method objects upon such retrieval isdescribed above, under “User-defined methods”. Class method objects are createdby the built-in classmethod() constructor.3.3. New-style and classic classes?Classes and instances come in two flavors: old-style (or classic) and new-style.Up to Python 2.1, old-style classes were the only flavour available to the user.The concept of (old-style) class is unrelated to the concept of type: if x isan instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always 'instance'>. This reflects the factthat all old-style instances, independently of their class, are implemented witha single built-in type, called instance.New-style classes were introduced in Python 2.2 to unify classes and types. Anew-style class is neither more nor less than a user-defined type. If x is aninstance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed - a new-style class instance ispermitted to override the value returned for x.__class__).The major motivation for introducing new-style classes is to provide a unifiedobject model with a full meta-model. It also has a number of practicalbenefits, like the ability to subclass most built-in types, or the introductionof “descriptors”, which enable computed properties.For compatibility reasons, classes are still old-style by default. New-styleclasses are created by specifying another new-style class (i.e. a type) as aparent class, or the “top-level type” object if no other parent isneeded. The behaviour of new-style classes differs from that of old-styleclasses in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, likethe way special methods are invoked. Others are “fixes” that could not beimplemented before for compatibility concerns, like the method resolution orderin case of multiple inheritance.While this manual aims to provide comprehensive coverage of Python’s classmechanics, it may still be lacking in some areas when it comes to its coverageof new-style classes. Please see http://www.python.org/doc/newstyle/ forsources of additional information.Old-style classes are removed in Python 3.0, leaving only the semantics ofnew-style classes.3.4. Special method names?A class can implement certain operations that are invoked by special syntax(such as arithmetic operations or subscripting and slicing) by defining methodswith special names. This is Python’s approach to operator overloading,allowing classes to define their own behavior with respect to languageoperators. For instance, if a class defines a method named __getitem__(),and x is an instance of this class, then x[i] is roughly equivalentto x.__getitem__(i) for old-style classes and type(x).__getitem__(x, i) for new-style classes. Except where mentioned, attempts to execute anoperation raise an exception when no appropriate method is defined (typically AttributeError or TypeError).When implementing a class that emulates any built-in type, it is important thatthe emulation only be implemented to the degree that it makes sense for theobject being modelled. For example, some sequences may work well with retrievalof individual elements, but extracting a slice may not make sense. (One exampleof this is the NodeList interface in the W3C’s Document Object Model.)3.4.1. Basic customization? object.__new__(cls[, ...])?Called to create a new instance of class cls. __new__() is a staticmethod (special-cased so you need not declare it as such) that takes the classof which an instance was requested as its first argument. The remainingarguments are those passed to the object constructor expression (the call to theclass). The return value of __new__() should be the new object instance(usually an instance of cls).Typical implementations create a new instance of the class by invoking thesuperclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying thenewly-created instance as necessary before returning it.If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as werepassed to __new__().If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.__new__() is intended mainly to allow subclasses of immutable types (likeint, str, or tuple) to customize instance creation. It is also commonlyoverridden in custom metaclasses in order to customize class creation.object.__init__(self[, ...])?Called when the instance is created. The arguments are those passed to theclass constructor expression. If a base class has an __init__() method,the derived class’s __init__() method, if any, must explicitly call it toensure proper initialization of the base class part of the instance; forexample: BaseClass.__init__(self, [args...]). As a special constraint onconstructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.object.__del__(self)?Called when the instance is about to be destroyed. This is also called adestructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure properdeletion of the base class part of the instance. Note that it is possible(though not recommended!) for the __del__() method to postpone destructionof the instance by creating a new reference to it. It may then be called at alater time when this new reference is deleted. It is not guaranteed that __del__() methods are called for objects that still exist when theinterpreter exits.Notedel x doesn’t directly call x.__del__() — the former decrementsthe reference count for x by one, and the latter is only called when x‘s reference count reaches zero. Some common situations that mayprevent the reference count of an object from going to zero include:circular references between objects (e.g., a doubly-linked list or a treedata structure with parent and child pointers); a reference to the objecton the stack frame of a function that caught an exception (the tracebackstored in sys.exc_traceback keeps the stack frame alive); or areference to the object on the stack frame that raised an unhandledexception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive). The first situationcan only be remedied by explicitly breaking the cycles; the latter twosituations can be resolved by storing None in sys.exc_traceback or sys.last_traceback. Circular references which are garbage aredetected when the option cycle detector is enabled (it’s on by default),but can only be cleaned up if there are no Python-level __del__() methods involved. Refer to the documentation for the gc module formore information about how __del__() methods are handled by thecycle detector, particularly the description of the garbage value.WarningDue to the precarious circumstances under which __del__() methods areinvoked, exceptions that occur during their execution are ignored, and a warningis printed to sys.stderr instead. Also, when __del__() is invoked inresponse to a module being deleted (e.g., when execution of the program isdone), other globals referenced by the __del__() method may already havebeen deleted or in the process of being torn down (e.g. the importmachinery shutting down). For this reason, __del__() methodsshould do the absoluteminimum needed to maintain external invariants. Starting with version 1.5,Python guarantees that globals whose name begins with a single underscore aredeleted from their module before other globals are deleted; if no otherreferences to such globals exist, this may help in assuring that importedmodules are still available at the time when the __del__() method iscalled.object.__repr__(self)?Called by the repr() built-in function and by string conversions (reversequotes) to compute the “official” string representation of an object. If at allpossible, this should look like a valid Python expression that could be used torecreate an object with the same value (given an appropriate environment). Ifthis is not possible, a string of the form useful description...> should be returned. The return value must be a string object. If a classdefines __repr__() but not __str__(), then __repr__() is alsoused when an “informal” string representation of instances of that class isrequired.This is typically used for debugging, so it is important that the representationis information-rich and unambiguous.object.__str__(self)?Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. Thisdiffers from __repr__() in that it does not have to be a valid Pythonexpression: a more convenient or concise representation may be used instead.The return value must be a string object.object.__lt__(self, other)? object.__le__(self, other)? object.__eq__(self, other)? object.__ne__(self, other)? object.__gt__(self, other)? object.__ge__(self, other)?New in version 2.1.These are the so-called “rich comparison” methods, and are called for comparisonoperators in preference to __cmp__() below. The correspondence betweenoperator symbols and method names is as follows: xx.__lt__(y), x calls x.__le__(y), x==y calls x.__eq__(y), x!=y and xy call x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).A rich comparison method may return the singleton NotImplemented if it doesnot implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, thesemethods can return any value, so if the comparison operator is used in a Booleancontext (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.There are no implied relationships among the comparison operators. The truthof x==y does not imply that x!=y is false. Accordingly, whendefining __eq__(), one should also define __ne__() so that theoperators will behave as expected. See the paragraph on __hash__() forsome important notes on creating hashable objects which supportcustom comparison operations and are usable as dictionary keys.There are no swapped-argument versions of these methods (to be used when theleft argument does not support the operation but the right argument does);rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection.Arguments to rich comparison methods are never coerced.To automatically generate ordering operations from a single root operation,see the Total Ordering recipe in the ASPN cookbook.object.__cmp__(self, other)?Called by comparison operations if rich comparison (see above) is notdefined. Should return a negative integer if self other, zero if self == other, a positive integer if self > other. If no __cmp__(), __eq__() or __ne__() operation is defined, classinstances are compared by object identity (“address”). See also thedescription of __hash__() for some important notes on creating hashable objects which support custom comparison operations and areusable as dictionary keys. (Note: the restriction that exceptions are notpropagated by __cmp__() has been removed since Python 1.5.)object.__rcmp__(self, other)?Changed in version 2.1: No longer supported.object.__hash__(self)?Called by built-in function hash() and for operations on members ofhashed collections including set, frozenset, and dict. __hash__() should return an integer. The only requiredproperty is that objects which compare equal have the same hash value; it isadvised to somehow mix together (e.g. using exclusive or) the hash values forthe components of the object that also play a part in comparison of objects.If a class does not define a __cmp__() or __eq__() method itshould not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instanceswill not be usable in hashed collections. If a class defines mutable objectsand implements a __cmp__() or __eq__() method, it should notimplement __hash__(), since hashable collection implementations requirethat a object’s hash value is immutable (if the object’s hash value changes,it will be in the wrong hash bucket).User-defined classes have __cmp__() and __hash__() methodsby default; with them, all objects compare unequal (except with themselves)and x.__hash__() returns id(x).Classes which inherit a __hash__() method from a parent class butchange the meaning of __cmp__() or __eq__() such that the hashvalue returned is no longer appropriate (e.g. by switching to a value-basedconcept of equality instead of the default identity based equality) canexplicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of theclass raise an appropriate TypeError when a program attempts toretrieve their hash value, but they will also be correctly identified asunhashable when checking isinstance(obj, collections.Hashable) (unlikeclasses which define their own __hash__() to explicitly raise TypeError).Changed in version 2.5: __hash__() may now also return a long integer object; the 32-bitinteger is then derived from the hash of that object.Changed in version 2.6: __hash__ may now be set to None to explicitly flaginstances of a class as unhashable.object.__nonzero__(self)?Called to implement truth value testing and the built-in operation bool();should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it isdefined, and the object is considered true if its result is nonzero.If a class defines neither __len__() nor __nonzero__(), all itsinstances are considered true.object.__unicode__(self)?Called to implement unicode() built-in; should return a Unicode object.When this method is not defined, string conversion is attempted, and the resultof string conversion is converted to Unicode using the system default encoding.3.4.2. Customizing attribute access?The following methods can be defined to customize the meaning of attributeaccess (use of, assignment to, or deletion of x.name) for class instances.object.__getattr__(self, name)?Called when an attribute lookup has not found the attribute in the usual places(i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the(computed) attribute value or raise an AttributeError exception.Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiencyreasons and because otherwise __getattr__() would have no way to accessother attributes of the instance. Note that at least for instance variables,you can fake total control by not inserting any values in the instance attributedictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control innew-style classes.object.__setattr__(self, name, value)?Called when an attribute assignment is attempted. This is called instead of thenormal mechanism (i.e. store the value in the instance dictionary). name isthe attribute name, value is the value to be assigned to it.If __setattr__() wants to assign to an instance attribute, it should notsimply execute self.name = value — this would cause a recursive call toitself. Instead, it should insert the value in the dictionary of instanceattributes, e.g., self.__dict__[name] = value. For new-style classes,rather than accessing the instance dictionary, it should call the base classmethod with the same name, for example, object.__setattr__(self, name, value).object.__delattr__(self, name)?Like __setattr__() but for attribute deletion instead of assignment. Thisshould only be implemented if del obj.name is meaningful for the object.3.4.2.1. More attribute access for new-style classes?The following methods only apply to new-style classes.object.__getattribute__(self, name)?Called unconditionally to implement attribute accesses for instances of theclass. If the class also defines __getattr__(), the latter will not becalled unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute valueor raise an AttributeError exception. In order to avoid infiniterecursion in this method, its implementation should always call the base classmethod with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).NoteThis method may still be bypassed when looking up special methods as theresult of implicit invocation via language syntax or built-in functions.See Special method lookup for new-style classes.3.4.2.2. Implementing Descriptors?The following methods only apply when an instance of the class containing themethod (a so-called descriptor class) appears in the class dictionary ofanother new-style class, known as the owner class. In the examples below, “theattribute” refers to the attribute whose name is the key of the property in theowner class’ __dict__. Descriptors can only be implemented as new-styleclasses themselves.object.__get__(self, instance, owner)?Called to get the attribute of the owner class (class attribute access) or of aninstance of that class (instance attribute access). owner is always the ownerclass, while instance is the instance that the attribute was accessed through,or None when the attribute is accessed through the owner. This methodshould return the (computed) attribute value or raise an AttributeError exception.object.__set__(self, instance, value)?Called to set the attribute on an instance instance of the owner class to anew value, value.object.__delete__(self, instance)?Called to delete the attribute on an instance instance of the owner class.3.4.2.3. Invoking Descriptors?In general, a descriptor is an object attribute with “binding behavior”, onewhose attribute access has been overridden by methods in the descriptorprotocol: __get__(), __set__(), and __delete__(). If any ofthose methods are defined for an object, it is said to be a descriptor.The default behavior for attribute access is to get, set, or delete theattribute from an object’s dictionary. For instance, a.x has a lookup chainstarting with a.__dict__['x'], then type(a).__dict__['x'], andcontinuing through the base classes of type(a) excluding metaclasses.However, if the looked-up value is an object defining one of the descriptormethods, then Python may override the default behavior and invoke the descriptormethod instead. Where this occurs in the precedence chain depends on whichdescriptor methods were defined and how they were called. Note that descriptorsare only invoked for new style objects or classes (ones that subclass object() or type()).The starting point for descriptor invocation is a binding, a.x. How thearguments are assembled depends on a:Direct CallThe simplest and least common call is when user code directly invokes adescriptor method: x.__get__(a).Instance BindingIf binding to a new-style object instance, a.x is transformed into the call: type(a).__dict__['x'].__get__(a, type(a)).Class BindingIf binding to a new-style class, A.x is transformed into the call: A.__dict__['x'].__get__(None, A).Super BindingIf a is an instance of super, then the binding super(B, obj).m() searches obj.__class__.__mro__ for the base class A immediately preceding B and then invokes the descriptor with the call: A.__dict__['m'].__get__(obj, A).For instance bindings, the precedence of descriptor invocation depends on thewhich descriptor methods are defined. Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. Data descriptors always override a redefinition in aninstance dictionary. In contrast, non-data descriptors can be overridden byinstances. [2]Python methods (including staticmethod() and classmethod()) areimplemented as non-data descriptors. Accordingly, instances can redefine andoverride methods. This allows individual instances to acquire behaviors thatdiffer from other instances of the same class.The property() function is implemented as a data descriptor. Accordingly,instances cannot override the behavior of a property.3.4.2.4. __slots__?By default, instances of both old and new-style classes have a dictionary forattribute storage. This wastes space for objects having very few instancevariables. The space consumption can become acute when creating large numbersof instances.The default can be overridden by defining __slots__ in a new-style classdefinition. The __slots__ declaration takes a sequence of instance variablesand reserves just enough space in each instance to hold a value for eachvariable. Space is saved because __dict__ is not created for each instance.__slots__?This class variable can be assigned a string, iterable, or sequence of stringswith variable names used by instances. If defined in a new-style class, __slots__ reserves space for the declared variables and prevents the automaticcreation of __dict__ and __weakref__ for each instance.New in version 2.2.Notes on using __slots__When inheriting from a class without __slots__, the __dict__ attribute ofthat class will always be accessible, so a __slots__ definition in thesubclass is meaningless.Without a __dict__ variable, instances cannot be assigned new variables notlisted in the __slots__ definition. Attempts to assign to an unlistedvariable name raises AttributeError. If dynamic assignment of newvariables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration.Changed in version 2.3: Previously, adding '__dict__' to the __slots__ declaration would notenable the assignment of new attributes not specifically listed in the sequenceof instance variable names.Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak referencesupport is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration.Changed in version 2.3: Previously, adding '__weakref__' to the __slots__ declaration would notenable support for weak references.__slots__ are implemented at the class level by creating descriptors(Implementing Descriptors) for each variable name. As a result, class attributescannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptorassignment.The action of a __slots__ declaration is limited to the class where it isdefined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).If a class defines a slot also defined in a base class, the instance variabledefined by the base class slot is inaccessible (except by retrieving itsdescriptor directly from the base class). This renders the meaning of theprogram undefined. In the future, a check may be added to prevent this.Nonempty __slots__ does not work for classes derived from “variable-length”built-in types such as long, str and tuple.Any non-string iterable may be assigned to __slots__. Mappings may also beused; however, in the future, special meaning may be assigned to the valuescorresponding to each key.__class__ assignment works only if both classes have the same __slots__.Changed in version 2.6: Previously, __class__ assignment raised an error if either new or old classhad __slots__.3.4.3. Customizing class creation?By default, new-style classes are constructed using type(). A classdefinition is read into a separate namespace and the value of class name isbound to the result of type(name, bases, dict).When the class definition is read, if __metaclass__ is defined then thecallable assigned to it will be called instead of type(). This allowsclasses or functions to be written which monitor or alter the class creationprocess:Modifying the class dictionary prior to the class being created.Returning an instance of another class – essentially performing the role of afactory function.These steps will have to be performed in the metaclass’s __new__() method– type.__new__() can then be called from this method to create a classwith different properties. This example adds a new element to the classdictionary before creating the class:class metacls(type):def __new__(mcs, name, bases, dict):dict['foo'] = 'metacls was here'return type.__new__(mcs, name, bases, dict)You can of course also override other class methods (or add new methods); forexample defining a custom __call__() method in the metaclass allows custombehavior when the class is called, e.g. not always creating a new instance.__metaclass__?This variable can be any callable accepting arguments for name, bases,and dict. Upon class creation, the callable is used instead of the built-in type().New in version 2.2.The appropriate metaclass is determined by the following precedence rules:If dict['__metaclass__'] exists, it is used.Otherwise, if there is at least one base class, its metaclass is used (thislooks for a __class__ attribute first and if not found, uses its type).Otherwise, if a global variable named __metaclass__ exists, it is used.Otherwise, the old-style, classic metaclass (types.ClassType) is used.The potential uses for metaclasses are boundless. Some ideas that have beenexplored including logging, interface checking, automatic delegation, automaticproperty creation, proxies, frameworks, and automatic resourcelocking/synchronization.3.4.4. Emulating callable objects? object.__call__(self[, args...])?Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).3.4.5. Emulating container types?The following methods can be defined to implement container objects. Containersusually are sequences (such as lists or tuples) or mappings (like dictionaries),but can represent other containers as well. The first set of methods is usedeither to emulate a sequence or to emulate a mapping; the difference is that fora sequence, the allowable keys should be the integers k for which 0 k N where N is the length of the sequence, or slice objects, which define arange of items. (For backwards compatibility, the method __getslice__() (see below) can also be defined to handle simple, but not extended slices.) Itis also recommended that mappings provide the methods keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update() behaving similarto those for Python’s standard dictionary objects. The UserDict moduleprovides a DictMixin class to help create those methods from a base setof __getitem__(), __setitem__(), __delitem__(), and keys(). Mutable sequences should provide methods append(), count(), index(), extend(), insert(), pop(), remove(), reverse() and sort(), like Python standard listobjects. Finally, sequence types should implement addition (meaningconcatenation) and multiplication (meaning repetition) by defining the methods __add__(), __radd__(), __iadd__(), __mul__(), __rmul__() and __imul__() described below; they should not define __coerce__() or other numerical operators. It is recommended that bothmappings and sequences implement the __contains__() method to allowefficient use of the in operator; for mappings, in should be equivalentof has_key(); for sequences, it should search through the values. It isfurther recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; formappings, __iter__() should be the same as iterkeys(); forsequences, it should iterate through the values.object.__len__(self)?Called to implement the built-in function len(). Should return the lengthof the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() method and whose __len__() method returns zero isconsidered to be false in a Boolean context.object.__getitem__(self, key)?Called to implement evaluation of self[key]. For sequence types, theaccepted keys should be integers and slice objects. Note that the specialinterpretation of negative indexes (if the class wishes to emulate a sequencetype) is up to the __getitem__() method. If key is of an inappropriatetype, TypeError may be raised; if of a value outside the set of indexesfor the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (notin the container), KeyError should be raised.Notefor loops expect that an IndexError will be raised for illegalindexes to allow proper detection of the end of the sequence.object.__setitem__(self, key, value)?Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if theobjects support changes to the values for keys, or if new keys can be added, orfor sequences if elements can be replaced. The same exceptions should be raisedfor improper key values as for the __getitem__() method.object.__delitem__(self, key)?Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if theobjects support removal of keys, or for sequences if elements can be removedfrom the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method.object.__iter__(self)?This method is called when an iterator is required for a container. This methodshould return a new iterator object that can iterate over all the objects in thecontainer. For mappings, it should iterate over the keys of the container, andshould also be made available as the method iterkeys().Iterator objects also need to implement this method; they are required to returnthemselves. For more information on iterator objects, see Iterator Types.object.__reversed__(self)?Called (if present) by the reversed() built-in to implementreverse iteration. It should return a new iterator object that iteratesover all the objects in the container in reverse order.If the __reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol (__len__() and __getitem__()). Objects that support the sequence protocol shouldonly provide __reversed__() if they can provide an implementationthat is more efficient than the one provided by reversed().New in version 2.6.The membership test operators (in and not in) are normallyimplemented as an iteration through a sequence. However, container objects cansupply the following special method with a more efficient implementation, whichalso does not require the object be a sequence.object.__contains__(self, item)?Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider thekeys of the mapping rather than the values or the key-item pairs.For objects that don’t define __contains__(), the membership test firsttries iteration via __iter__(), then the old sequence iterationprotocol via __getitem__(), see this section in the languagereference.3.4.6. Additional methods for emulation of sequence types?The following optional methods can be defined to further emulate sequenceobjects. Immutable sequences methods should at most only define __getslice__(); mutable sequences might define all three methods.object.__getslice__(self, i, j)?Deprecated since version 2.0: Support slice objects as parameters to the __getitem__() method.(However, built-in types in CPython currently still implement __getslice__(). Therefore, you have to override it in derivedclasses when implementing slicing.)Called to implement evaluation of self[i:j]. The returned object should beof the same type as self. Note that missing i or j in the sliceexpression are replaced by zero or sys.maxint, respectively. If negativeindexes are used in the slice, the length of the sequence is added to thatindex. If the instance does not implement the __len__() method, an AttributeError is raised. No guarantee is made that indexes adjusted thisway are not still negative. Indexes which are greater than the length of thesequence are not modified. If no __getslice__() is found, a slice objectis created instead, and passed to __getitem__() instead.object.__setslice__(self, i, j, sequence)?Called to implement assignment to self[i:j]. Same notes for i and j asfor __getslice__().This method is deprecated. If no __setslice__() is found, or for extendedslicing of the form self[i:j:k], a slice object is created, and passed to __setitem__(), instead of __setslice__() being called.object.__delslice__(self, i, j)?Called to implement deletion of self[i:j]. Same notes for i and j as for __getslice__(). This method is deprecated. If no __delslice__() isfound, or for extended slicing of the form self[i:j:k], a slice object iscreated, and passed to __delitem__(), instead of __delslice__() being called.Notice that these methods are only invoked when a single slice with a singlecolon is used, and the slice method is available. For slice operationsinvolving extended slice notation, or in absence of the slice methods, __getitem__(), __setitem__() or __delitem__() is called with aslice object as argument.The following example demonstrate how to make your program or module compatiblewith earlier versions of Python (assuming that methods __getitem__(), __setitem__() and __delitem__() support slice objects asarguments):class MyClass:...def __getitem__(self, index):...def __setitem__(self, index, value):...def __delitem__(self, index):...if sys.version_info (2, 0):# They won't be defined if version is at least 2.0 finaldef __getslice__(self, i, j):return self[max(0, i):max(0, j):]def __setslice__(self, i, j, seq):self[max(0, i):max(0, j):] = seqdef __delslice__(self, i, j):del self[max(0, i):max(0, j):]...Note the calls to max(); these are necessary because of the handling ofnegative indices before the __*slice__() methods are called. Whennegative indexes are used, the __*item__() methods receive them asprovided, but the __*slice__() methods get a “cooked” form of the indexvalues. For each negative index value, the length of the sequence is added tothe index before calling the method (which may still result in a negativeindex); this is the customary handling of negative indexes by the built-insequence types, and the __*item__() methods are expected to do this aswell. However, since they should already be doing that, negative indexes cannotbe passed in; they must be constrained to the bounds of the sequence beforebeing passed to the __*item__() methods. Calling max(0, i) conveniently returns the proper value.3.4.7. Emulating numeric types?The following methods can be defined to emulate numeric objects. Methodscorresponding to operations that are not supported by the particular kind ofnumber implemented (e.g., bitwise operations for non-integral numbers) should beleft undefined.object.__add__(self, other)? object.__sub__(self, other)? object.__mul__(self, other)? object.__floordiv__(self, other)? object.__mod__(self, other)? object.__divmod__(self, other)? object.__pow__(self, other[, modulo])? object.__lshift__(self, other)? object.__rshift__(self, other)? object.__and__(self, other)? object.__xor__(self, other)? object.__or__(self, other)?These methods are called to implement the binary arithmetic operations (+, -, *, //, %, divmod(), pow(), **, , >>, &, ^, |). For instance, to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called. The __divmod__() method should be theequivalent to using __floordiv__() and __mod__(); it should not berelated to __truediv__() (described below). Note that __pow__() should be defined to accept an optional third argument if the ternary version ofthe built-in pow() function is to be supported.If one of those methods does not support the operation with the suppliedarguments, it should return NotImplemented.object.__div__(self, other)? object.__truediv__(self, other)?The division operator (/) is implemented by these methods. The __truediv__() method is used when __future__.division is in effect,otherwise __div__() is used. If only one of these two methods is defined,the object will not support division in the alternate context; TypeError will be raised instead.object.__radd__(self, other)? object.__rsub__(self, other)? object.__rmul__(self, other)? object.__rdiv__(self, other)? object.__rtruediv__(self, other)? object.__rfloordiv__(self, other)? object.__rmod__(self, other)? object.__rdivmod__(self, other)? object.__rpow__(self, other)? object.__rlshift__(self, other)? object.__rrshift__(self, other)? object.__rand__(self, other)? object.__rxor__(self, other)? object.__ror__(self, other)?These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, , >>, &, ^, |) with reflected (swapped) operands. These functions areonly called if the left operand does not support the corresponding operation andthe operands are of different types. [3] For instance, to evaluate theexpression x - y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.Note that ternary pow() will not try calling __rpow__() (thecoercion rules would become too complicated).NoteIf the right operand’s type is a subclass of the left operand’s type and thatsubclass provides the reflected method for the operation, this method will becalled before the left operand’s non-reflected method. This behavior allowssubclasses to override their ancestors’ operations.object.__iadd__(self, other)? object.__isub__(self, other)? object.__imul__(self, other)? object.__idiv__(self, other)? object.__itruediv__(self, other)? object.__ifloordiv__(self, other)? object.__imod__(self, other)? object.__ipow__(self, other[, modulo])? object.__ilshift__(self, other)? object.__irshift__(self, other)? object.__iand__(self, other)? object.__ixor__(self, other)? object.__ior__(self, other)?These methods are called to implement the augmented arithmetic assignments(+=, -=, *=, /=, //=, %=, **=, >>=, &=, ^=, |=). These methods should attempt to do the operationin-place (modifying self) and return the result (which could be, but doesnot have to be, self). If a specific method is not defined, the augmentedassignment falls back to the normal methods. For instance, to execute thestatement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. If x is an instanceof a class that does not define a __iadd__() method, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y.object.__neg__(self)? object.__pos__(self)? object.__abs__(self)? object.__invert__(self)?Called to implement the unary arithmetic operations (-, +, abs() and ~).object.__complex__(self)? object.__int__(self)? object.__long__(self)? object.__float__(self)?Called to implement the built-in functions complex(), int(), long(), and float(). Should return a value of the appropriate type.object.__oct__(self)? object.__hex__(self)?Called to implement the built-in functions oct() and hex(). Shouldreturn a string value.object.__index__(self)?Called to implement operator.index(). Also called whenever Python needsan integer object (such as in slicing). Must return an integer (int or long).New in version 2.5.object.__coerce__(self, other)?Called to implement “mixed-mode” numeric arithmetic. Should either return a2-tuple containing self and other converted to a common numeric type, or None if conversion is impossible. When the common type would be the type of other, it is sufficient to return None, since the interpreter will alsoask the other object to attempt a coercion (but sometimes, if the implementationof the other type cannot be changed, it is useful to do the conversion to theother type here). A return value of NotImplemented is equivalent toreturning None.3.4.8. Coercion rules?This section used to document the rules for coercion. As the language hasevolved, the coercion rules have become hard to document precisely; documentingwhat one version of one particular implementation does is undesirable. Instead,here are some informal guidelines regarding coercion. In Python 3.0, coercionwill not be supported.If the left operand of a % operator is a string or Unicode object, no coerciontakes place and the string formatting operation is invoked instead.It is no longer recommended to define a coercion operation. Mixed-modeoperations on types that don’t define coercion pass the original arguments tothe operation.New-style classes (those derived from object) never invoke the __coerce__() method in response to a binary operator; the only time __coerce__() is invoked is when the built-in function coerce() iscalled.For most intents and purposes, an operator that returns NotImplemented istreated the same as one that is not implemented at all.Below, __op__() and __rop__() are used to signify the generic methodnames corresponding to an operator; __iop__() is used for thecorresponding in-place operator. For example, for the operator ‘+‘, __add__() and __radd__() are used for the left and right variant ofthe binary operator, and __iadd__() for the in-place variant.For objects x and y, first x.__op__(y) is tried. If this is notimplemented or returns NotImplemented, y.__rop__(x) is tried. If thisis also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception:Exception to the previous item: if the left operand is an instance of a built-intype or a new-style class, and the right operand is an instance of a propersubclass of that type or class and overrides the base’s __rop__() method,the right operand’s __rop__() method is tried before the left operand’s __op__() method.This is done so that a subclass can completely override binary operators.Otherwise, the left operand’s __op__() method would always accept theright operand: when an instance of a given class is expected, an instance of asubclass of that class is always acceptable.When either operand type defines a coercion, this coercion is called before thattype’s __op__() or __rop__() method is called, but no sooner. Ifthe coercion returns an object of a different type for the operand whosecoercion is invoked, part of the process is redone using the new object.When an in-place operator (like ‘+=‘) is used, if the left operandimplements __iop__(), it is invoked without any coercion. When theoperation falls back to __op__() and/or __rop__(), the normalcoercion rules apply.In x + y, if x is a sequence that implements sequence concatenation,sequence concatenation is invoked.In x * y, if one operator is a sequence that implements sequencerepetition, and the other is an integer (int or long),sequence repetition is invoked.Rich comparisons (implemented by methods __eq__() and so on) never usecoercion. Three-way comparison (implemented by __cmp__()) does usecoercion under the same conditions as other binary operations use it.In the current implementation, the built-in numeric types int, long and float do not use coercion; the type complex however does use coercion for binary operators and rich comparisons, despitethe above rules. The difference can become apparent when subclassing thesetypes. Over time, the type complex may be fixed to avoid coercion.All these types implement a __coerce__() method, for use by the built-in coerce() function.3.4.9. With Statement Context Managers?New in version 2.5.A context manager is an object that defines the runtime context to beestablished when executing a with statement. The context managerhandles the entry into, and the exit from, the desired runtime context for theexecution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also beused by directly invoking their methods.Typical uses of context managers include saving and restoring various kinds ofglobal state, locking and unlocking resources, closing opened files, etc.For more information on context managers, see Context Manager Types.object.__enter__(self)?Enter the runtime context related to this object. The with statementwill bind this method’s return value to the target(s) specified in the as clause of the statement, if any.object.__exit__(self, exc_type, exc_value, traceback)?Exit the runtime context related to this object. The parameters describe theexception that caused the context to be exited. If the context was exitedwithout an exception, all three arguments will be None.If an exception is supplied, and the method wishes to suppress the exception(i.e., prevent it from being propagated), it should return a true value.Otherwise, the exception will be processed normally upon exit from this method.Note that __exit__() methods should not reraise the passed-in exception;this is the caller’s responsibility.See alsoPEP 0343 - The “with” statementThe specification, background, and examples for the Python with statement.3.4.10. Special method lookup for old-style classes?For old-style classes, special methods are always looked up in exactly thesame way as any other method or attribute. This is the case regardless ofwhether the method is being looked up explicitly as in x.__getitem__(i) or implicitly as in x[i].This behaviour means that special methods may exhibit different behaviourfor different instances of a single old-style class if the appropriatespecial attributes are set differently:>>> class C:... pass...>>> c1 = C()>>> c2 = C()>>> c1.__len__ = lambda: 5>>> c2.__len__ = lambda: 9>>> len(c1)5>>> len(c2)93.4.11. Special method lookup for new-style classes?For new-style classes, implicit invocations of special methods are only guaranteedto work correctly if defined on an object’s type, not in the object’s instancedictionary. That behaviour is the reason why the following code raises anexception (unlike the equivalent example with old-style classes):>>> class C(object):... pass...>>> c = C()>>> c.__len__ = lambda: 5>>> len(c)Traceback (most recent call last):File "", line 1, inTypeError: object of type 'C' has no len()The rationale behind this behaviour lies with a number of special methods suchas __hash__() and __repr__() that are implemented by all objects,including type objects. If the implicit lookup of these methods used theconventional lookup process, they would fail when invoked on the type objectitself:>>> 1 .__hash__() == hash(1)True>>> int.__hash__() == hash(int)Traceback (most recent call last):File "", line 1, inTypeError: descriptor '__hash__' of 'int' object needs an argumentIncorrectly attempting to invoke an unbound method of a class in this way issometimes referred to as ‘metaclass confusion’, and is avoided by bypassingthe instance when looking up special methods:>>> type(1).__hash__(1) == hash(1)True>>> type(int).__hash__(int) == hash(int)TrueIn addition to bypassing any instance attributes in the interest ofcorrectness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass:>>> class Meta(type):... def __getattribute__(*args):... print "Metaclass getattribute invoked"... return type.__getattribute__(*args)...>>> class C(object):... __metaclass__ = Meta... def __len__(self):... return 10... def __getattribute__(*args):... print "Class getattribute invoked"... return object.__getattribute__(*args)...>>> c = C()>>> c.__len__() # Explicit lookup via instanceClass getattribute invoked10>>> type(c).__len__(c) # Explicit lookup via typeMetaclass getattribute invoked10>>> len(c) # Implicit lookup10Bypassing the __getattribute__() machinery in this fashionprovides significant scope for speed optimisations within theinterpreter, at the cost of some flexibility in the handling ofspecial methods (the special method must be set on the classobject itself in order to be consistently invoked by the interpreter).Footnotes[1]It is possible in some cases to change an object’s type, under certaincontrolled conditions. It generally isn’t a good idea though, since it canlead to some very strange behaviour if it is handled incorrectly.[2]A descriptor can define any combination of __get__(), __set__() and __delete__(). If it does not define __get__(),then accessing the attribute even on an instance will return the descriptorobject itself. If the descriptor defines __set__() and/or __delete__(), it is a data descriptor; if it defines neither, it is anon-data descriptor.[3]For operands of the same type, it is assumed that if the non-reflected method(such as __add__()) fails the operation is not supported, which is why thereflected method is not called.
12-28 12:10