Next: Special method names Up: Data model Previous: Objectsvalues and

The standard type hierarchy

Below is a list of the types that are built into Python. Extension modules written in C can define additional types. Future versions of Python may add types to the type hierarchy (e.g. rational or complex numbers, efficiently stored arrays of integers, etc.).

Some of the type descriptions below contain a paragraph listing `special attributes'. These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future. There are also some `generic' special attributes, not listed with the individual objects: __methods__ is a list of the method names of a built-in object, if it has any; __members__ is a list of the data attribute names of a built-in object, if it has any.

None
This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is returned from functions that don't explicitly return an object.

Numbers
These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers.

Python distinguishes between integers and floating point numbers:

Integers
These represent elements from the mathematical set of whole numbers.

There are two types of integers:

Plain integers
These represent numbers in the range [tex2html_wrap1110]through [tex2html_wrap1112]. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation falls outside this range, the exception OverflowError is raised. For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all [tex2html_wrap1114]different bit patterns correspond to different values).

Long integers
These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left.

The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. For any operation except left shift, if it yields a result in the plain integer domain without causing overflow, it will yield the same result in the long integer domain or when using mixed operands.

Floating point numbers
These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture and C implementation for the accepted range and handling of overflow.

Sequences
These represent finite ordered sets indexed by natural numbers. The built-in function len() returns the number of elements of a sequence. When this number is [tex2html_wrap1116], the index set contains the numbers [tex2html_wrap1118]. Element i of sequence a is selected by a[i].

Sequences also support slicing: a[i:j] selects all elements with index [tex2html_wrap1120]such that [tex2html_wrap1122]. When used as an expression, a slice is a sequence of the same type - this implies that the index set is renumbered so that it starts at 0 again.

Sequences are distinguished according to their mutability:

Immutable sequences
An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however the collection of objects directly referenced by an immutable object cannot change.)

The following types are immutable sequences:

Strings
The elements of a string are characters. There is no separate character type; a character is represented by a string of one element. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 represent the corresponding ASCII values. The string data type is also used 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 in their internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)

Tuples
The elements of a tuple are arbitrary Python objects. Tuples of two or more elements are formed by comma-separated lists of expressions. A tuple of one element (a `singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by enclosing `nothing' in parentheses.

Mutable sequences
Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and del (delete) statements.

There is currently a single mutable sequence type:

Lists
The elements of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)

Mapping types
These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the element 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 number of elements in a mapping.

There is currently a single mapping type:

Dictionaries
These represent finite sets of objects indexed by almost arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity - the reason being that the implementation requires that a key's hash value be constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g. 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.

Dictionaries are mutable; they are created by the {...} notation (see section ).

Callable types
These are the types to which the function call (invocation) operation, written as function(argument, argument, ...), can be applied:

User-defined functions
A user-defined function object is created by a function definition (see section ). It should be called with an argument list containing the same number of items as the function's formal parameter list.

Special read-only attributes: func_code is the code object representing the compiled function body, and func_globals is (a reference to) the dictionary that holds the function's global variables - it implements the global name space of the module in which the function was defined.

User-defined methods
A user-defined method (a.k.a. object closure) is a pair of a class instance object and a user-defined function. It should be called with an argument list containing one item less than the number of items in the function's formal parameter list. When called, the class instance becomes the first argument, and the call arguments are shifted one to the right.

Special read-only attributes: im_self is the class instance object, im_func is the function object.

Built-in functions
A built-in function object is a wrapper around a C function. Examples of built-in functions are len and math.sin. There are no special attributes. The number and type of the arguments are determined by the C function.

Built-in methods
This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is list.append if list is a list object.

Classes
Class objects are described below. When a class object is called as a parameterless function, a new class instance (also described below) is created and returned. The class's initialization function is not called - this is the responsibility of the caller. It is illegal to call a class object with one or more arguments.

Modules
Modules are imported by the import statement (see section ). A module object is a container for a module's name space, which is a dictionary (the same dictionary as referenced by the func_globals attribute of functions defined in the module). Module attribute references are translated to lookups in this dictionary. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done).

Attribute assignment update the module's name space dictionary.

Special read-only attributes: __dict__ yields the module's name space as a dictionary object; __name__ yields the module's name as a string object.

Classes
Class objects are created by class definitions (see section ). A class is a container for a dictionary containing the class's name space. Class attribute references are translated to lookups in this dictionary. When an attribute name is not found there, the attribute search continues in the base classes. The search is depth-first, left-to-right in the order of their occurrence in the base class list.

Class attribute assignments update the class's dictionary, never the dictionary of a base class.

A class can be called as a parameterless function to yield a class instance (see above).

Special read-only attributes: __dict__ yields the dictionary containing the class's name space; __bases__ yields a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list.

Class instances
A class instance is created by calling a class object as a parameterless function. A class instance has a dictionary in which attribute references are searched. When an attribute is not found there, and the instance's class has an attribute by that name, and that class attribute is a user-defined function (and in no other cases), the instance attribute reference yields a user-defined method object (see above) constructed from the instance and the function.

Attribute assignments update the instance's dictionary.

Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. These are described in section .

Special read-only attributes: __dict__ yields the attribute dictionary; __class__ yields the instance's class.

Files
A file object represents an open file. (It is a wrapper around a C stdio file pointer.) File objects are created by the open() built-in function, and also by posix.popen() and the makefile method of socket objects. sys.stdin, sys.stdout and sys.stderr are file objects corresponding the the interpreter's standard input, output and error streams. See the Python Library Reference for methods of file objects and other details.

Internal types
A few types used internally by the interpreter are exposed to the user. Their definition may change with future versions of the interpreter, but they are mentioned here for completeness.

Code objects
Code objects represent executable code. The difference between a code object and a function object is that the function object contains an explicit reference to the function's context (the module in which it was defined) which a code object contains no context. There is no way to execute a bare code object.

Special read-only attributes: co_code is a string representing the sequence of instructions; co_consts is a list of literals used by the code; co_names is a list of names (strings) used by the code; co_filename is the filename from which the code was compiled. (To find out the line numbers, you would have to decode the instructions; the standard library module dis contains an example of how to do this.)

Frame objects
Frame 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_globals is the dictionary used to look up global variables; f_locals is used for local variables; f_lineno gives the line number and f_lasti gives the precise instruction (this is an index into the instruction string of the code object).

Traceback objects
Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered (see also section ), the stack trace is made available to the program as sys.exc_traceback. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter 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 stack trace (towards the frame where the exception occurred), or None if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.



Next: Special method names Up: Data model Previous: Objectsvalues and


guido@cwi.nl