blob: f4e3d63c29388c2a4034ff859533782342fe2feb [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _datamodel:
3
4**********
5Data model
6**********
7
8
9.. _objects:
10
11Objects, values and types
12=========================
13
14.. index::
15 single: object
16 single: data
17
18:dfn:`Objects` are Python's abstraction for data. All data in a Python program
19is represented by objects or by relations between objects. (In a sense, and in
20conformance to Von Neumann's model of a "stored program computer," code is also
21represented by objects.)
22
23.. index::
24 builtin: id
25 builtin: type
26 single: identity of an object
27 single: value of an object
28 single: type of an object
29 single: mutable object
30 single: immutable object
31
32Every object has an identity, a type and a value. An object's *identity* never
33changes once it has been created; you may think of it as the object's address in
34memory. The ':keyword:`is`' operator compares the identity of two objects; the
35:func:`id` function returns an integer representing its identity (currently
36implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
37An object's type determines the operations that the object supports (e.g., "does
38it have a length?") and also defines the possible values for objects of that
39type. The :func:`type` function returns an object's type (which is an object
40itself). The *value* of some objects can change. Objects whose value can
41change are said to be *mutable*; objects whose value is unchangeable once they
42are created are called *immutable*. (The value of an immutable container object
43that contains a reference to a mutable object can change when the latter's value
44is changed; however the container is still considered immutable, because the
45collection of objects it contains cannot be changed. So, immutability is not
46strictly the same as having an unchangeable value, it is more subtle.) An
47object's mutability is determined by its type; for instance, numbers, strings
48and tuples are immutable, while dictionaries and lists are mutable.
49
50.. index::
51 single: garbage collection
52 single: reference counting
53 single: unreachable object
54
55Objects are never explicitly destroyed; however, when they become unreachable
56they may be garbage-collected. An implementation is allowed to postpone garbage
57collection or omit it altogether --- it is a matter of implementation quality
58how garbage collection is implemented, as long as no objects are collected that
Georg Brandl6c14e582009-10-22 11:48:10 +000059are still reachable.
60
61.. impl-detail::
62
63 CPython currently uses a reference-counting scheme with (optional) delayed
64 detection of cyclically linked garbage, which collects most objects as soon
65 as they become unreachable, but is not guaranteed to collect garbage
66 containing circular references. See the documentation of the :mod:`gc`
67 module for information on controlling the collection of cyclic garbage.
68 Other implementations act differently and CPython may change.
Gregory P. Smith28d57c02011-03-10 11:49:27 -080069 Do not depend on immediate finalization of objects when they become
70 unreachable (ex: always close files).
Georg Brandl8ec7f652007-08-15 14:28:01 +000071
72Note that the use of the implementation's tracing or debugging facilities may
73keep objects alive that would normally be collectable. Also note that catching
74an exception with a ':keyword:`try`...\ :keyword:`except`' statement may keep
75objects alive.
76
77Some objects contain references to "external" resources such as open files or
78windows. It is understood that these resources are freed when the object is
79garbage-collected, but since garbage collection is not guaranteed to happen,
80such objects also provide an explicit way to release the external resource,
81usually a :meth:`close` method. Programs are strongly recommended to explicitly
82close such objects. The ':keyword:`try`...\ :keyword:`finally`' statement
83provides a convenient way to do this.
84
85.. index:: single: container
86
87Some objects contain references to other objects; these are called *containers*.
88Examples of containers are tuples, lists and dictionaries. The references are
89part of a container's value. In most cases, when we talk about the value of a
90container, we imply the values, not the identities of the contained objects;
91however, when we talk about the mutability of a container, only the identities
92of the immediately contained objects are implied. So, if an immutable container
93(like a tuple) contains a reference to a mutable object, its value changes if
94that mutable object is changed.
95
96Types affect almost all aspects of object behavior. Even the importance of
97object identity is affected in some sense: for immutable types, operations that
98compute new values may actually return a reference to any existing object with
99the same type and value, while for mutable objects this is not allowed. E.g.,
100after ``a = 1; b = 1``, ``a`` and ``b`` may or may not refer to the same object
101with the value one, depending on the implementation, but after ``c = []; d =
102[]``, ``c`` and ``d`` are guaranteed to refer to two different, unique, newly
103created empty lists. (Note that ``c = d = []`` assigns the same object to both
104``c`` and ``d``.)
105
106
107.. _types:
108
109The standard type hierarchy
110===========================
111
112.. index::
113 single: type
114 pair: data; type
115 pair: type; hierarchy
116 pair: extension; module
117 pair: C; language
118
119Below is a list of the types that are built into Python. Extension modules
120(written in C, Java, or other languages, depending on the implementation) can
121define additional types. Future versions of Python may add types to the type
122hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).
123
124.. index::
125 single: attribute
126 pair: special; attribute
127 triple: generic; special; attribute
128
129Some of the type descriptions below contain a paragraph listing 'special
130attributes.' These are attributes that provide access to the implementation and
131are not intended for general use. Their definition may change in the future.
132
133None
134 .. index:: object: None
135
136 This type has a single value. There is a single object with this value. This
137 object is accessed through the built-in name ``None``. It is used to signify the
138 absence of a value in many situations, e.g., it is returned from functions that
139 don't explicitly return anything. Its truth value is false.
140
141NotImplemented
142 .. index:: object: NotImplemented
143
144 This type has a single value. There is a single object with this value. This
145 object is accessed through the built-in name ``NotImplemented``. Numeric methods
146 and rich comparison methods may return this value if they do not implement the
147 operation for the operands provided. (The interpreter will then try the
148 reflected operation, or some other fallback, depending on the operator.) Its
149 truth value is true.
150
151Ellipsis
152 .. index:: object: Ellipsis
153
154 This type has a single value. There is a single object with this value. This
155 object is accessed through the built-in name ``Ellipsis``. It is used to
156 indicate the presence of the ``...`` syntax in a slice. Its truth value is
157 true.
158
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000159:class:`numbers.Number`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160 .. index:: object: numeric
161
162 These are created by numeric literals and returned as results by arithmetic
163 operators and arithmetic built-in functions. Numeric objects are immutable;
164 once created their value never changes. Python numbers are of course strongly
165 related to mathematical numbers, but subject to the limitations of numerical
166 representation in computers.
167
168 Python distinguishes between integers, floating point numbers, and complex
169 numbers:
170
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000171 :class:`numbers.Integral`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172 .. index:: object: integer
173
174 These represent elements from the mathematical set of integers (positive and
175 negative).
176
177 There are three types of integers:
178
179 Plain integers
180 .. index::
181 object: plain integer
182 single: OverflowError (built-in exception)
183
Georg Brandle9135ba2008-05-11 10:55:59 +0000184 These represent numbers in the range -2147483648 through 2147483647.
185 (The range may be larger on machines with a larger natural word size,
186 but not smaller.) When the result of an operation would fall outside
187 this range, the result is normally returned as a long integer (in some
188 cases, the exception :exc:`OverflowError` is raised instead). For the
189 purpose of shift and mask operations, integers are assumed to have a
190 binary, 2's complement notation using 32 or more bits, and hiding no
191 bits from the user (i.e., all 4294967296 different bit patterns
192 correspond to different values).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194 Long integers
195 .. index:: object: long integer
196
Georg Brandle9135ba2008-05-11 10:55:59 +0000197 These represent numbers in an unlimited range, subject to available
198 (virtual) memory only. For the purpose of shift and mask operations, a
199 binary representation is assumed, and negative numbers are represented
200 in a variant of 2's complement which gives the illusion of an infinite
201 string of sign bits extending to the left.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203 Booleans
204 .. index::
205 object: Boolean
206 single: False
207 single: True
208
Georg Brandle9135ba2008-05-11 10:55:59 +0000209 These represent the truth values False and True. The two objects
Serhiy Storchaka26d936a2013-11-29 12:16:53 +0200210 representing the values ``False`` and ``True`` are the only Boolean objects.
Georg Brandle9135ba2008-05-11 10:55:59 +0000211 The Boolean type is a subtype of plain integers, and Boolean values
212 behave like the values 0 and 1, respectively, in almost all contexts,
213 the exception being that when converted to a string, the strings
214 ``"False"`` or ``"True"`` are returned, respectively.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000215
216 .. index:: pair: integer; representation
217
Georg Brandle9135ba2008-05-11 10:55:59 +0000218 The rules for integer representation are intended to give the most
219 meaningful interpretation of shift and mask operations involving negative
220 integers and the least surprises when switching between the plain and long
221 integer domains. Any operation, if it yields a result in the plain
222 integer domain, will yield the same result in the long integer domain or
223 when using mixed operands. The switch between domains is transparent to
224 the programmer.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000226 :class:`numbers.Real` (:class:`float`)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227 .. index::
228 object: floating point
229 pair: floating point; number
230 pair: C; language
231 pair: Java; language
232
233 These represent machine-level double precision floating point numbers. You are
234 at the mercy of the underlying machine architecture (and C or Java
235 implementation) for the accepted range and handling of overflow. Python does not
236 support single-precision floating point numbers; the savings in processor and
237 memory usage that are usually the reason for using these is dwarfed by the
238 overhead of using objects in Python, so there is no reason to complicate the
239 language with two kinds of floating point numbers.
240
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000241 :class:`numbers.Complex`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242 .. index::
243 object: complex
244 pair: complex; number
245
246 These represent complex numbers as a pair of machine-level double precision
247 floating point numbers. The same caveats apply as for floating point numbers.
248 The real and imaginary parts of a complex number ``z`` can be retrieved through
249 the read-only attributes ``z.real`` and ``z.imag``.
250
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251Sequences
252 .. index::
253 builtin: len
254 object: sequence
255 single: index operation
256 single: item selection
257 single: subscription
258
259 These represent finite ordered sets indexed by non-negative numbers. The
260 built-in function :func:`len` returns the number of items of a sequence. When
261 the length of a sequence is *n*, the index set contains the numbers 0, 1,
262 ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``.
263
264 .. index:: single: slicing
265
266 Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such
267 that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a
268 sequence of the same type. This implies that the index set is renumbered so
269 that it starts at 0.
270
271 .. index:: single: extended slicing
272
273 Some sequences also support "extended slicing" with a third "step" parameter:
274 ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n*
275 ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*.
276
277 Sequences are distinguished according to their mutability:
278
279 Immutable sequences
280 .. index::
281 object: immutable sequence
282 object: immutable
283
284 An object of an immutable sequence type cannot change once it is created. (If
285 the object contains references to other objects, these other objects may be
286 mutable and may be changed; however, the collection of objects directly
287 referenced by an immutable object cannot change.)
288
289 The following types are immutable sequences:
290
291 Strings
292 .. index::
293 builtin: chr
294 builtin: ord
295 object: string
296 single: character
297 single: byte
298 single: ASCII@ASCII
299
300 The items of a string are characters. There is no separate character type; a
301 character is represented by a string of one item. Characters represent (at
302 least) 8-bit bytes. The built-in functions :func:`chr` and :func:`ord` convert
303 between characters and nonnegative integers representing the byte values. Bytes
304 with the values 0-127 usually represent the corresponding ASCII values, but the
305 interpretation of values is up to the program. The string data type is also
306 used to represent arrays of bytes, e.g., to hold data read from a file.
307
308 .. index::
309 single: ASCII@ASCII
310 single: EBCDIC
311 single: character set
312 pair: string; comparison
313 builtin: chr
314 builtin: ord
315
316 (On systems whose native character set is not ASCII, strings may use EBCDIC in
317 their internal representation, provided the functions :func:`chr` and
318 :func:`ord` implement a mapping between ASCII and EBCDIC, and string comparison
319 preserves the ASCII order. Or perhaps someone can propose a better rule?)
320
321 Unicode
322 .. index::
323 builtin: unichr
324 builtin: ord
325 builtin: unicode
326 object: unicode
327 single: character
328 single: integer
329 single: Unicode
330
331 The items of a Unicode object are Unicode code units. A Unicode code unit is
332 represented by a Unicode object of one item and can hold either a 16-bit or
333 32-bit value representing a Unicode ordinal (the maximum value for the ordinal
334 is given in ``sys.maxunicode``, and depends on how Python is configured at
335 compile time). Surrogate pairs may be present in the Unicode object, and will
336 be reported as two separate items. The built-in functions :func:`unichr` and
337 :func:`ord` convert between code units and nonnegative integers representing the
338 Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to
339 other encodings are possible through the Unicode method :meth:`encode` and the
340 built-in function :func:`unicode`.
341
342 Tuples
343 .. index::
344 object: tuple
345 pair: singleton; tuple
346 pair: empty; tuple
347
348 The items of a tuple are arbitrary Python objects. Tuples of two or more items
349 are formed by comma-separated lists of expressions. A tuple of one item (a
350 'singleton') can be formed by affixing a comma to an expression (an expression
351 by itself does not create a tuple, since parentheses must be usable for grouping
352 of expressions). An empty tuple can be formed by an empty pair of parentheses.
353
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354 Mutable sequences
355 .. index::
356 object: mutable sequence
357 object: mutable
358 pair: assignment; statement
359 single: delete
360 statement: del
361 single: subscription
362 single: slicing
363
364 Mutable sequences can be changed after they are created. The subscription and
365 slicing notations can be used as the target of assignment and :keyword:`del`
366 (delete) statements.
367
Benjamin Petersonb7464482009-01-18 01:28:46 +0000368 There are currently two intrinsic mutable sequence types:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
370 Lists
371 .. index:: object: list
372
373 The items of a list are arbitrary Python objects. Lists are formed by placing a
374 comma-separated list of expressions in square brackets. (Note that there are no
375 special cases needed to form lists of length 0 or 1.)
376
Benjamin Petersonf1a40692009-01-18 01:28:09 +0000377 Byte Arrays
378 .. index:: bytearray
379
380 A bytearray object is a mutable array. They are created by the built-in
381 :func:`bytearray` constructor. Aside from being mutable (and hence
382 unhashable), byte arrays otherwise provide the same interface and
383 functionality as immutable bytes objects.
384
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385 .. index:: module: array
386
387 The extension module :mod:`array` provides an additional example of a mutable
388 sequence type.
389
Georg Brandl2ce1c612009-03-31 19:14:42 +0000390Set types
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391 .. index::
392 builtin: len
393 object: set type
394
395 These represent unordered, finite sets of unique, immutable objects. As such,
396 they cannot be indexed by any subscript. However, they can be iterated over, and
397 the built-in function :func:`len` returns the number of items in a set. Common
398 uses for sets are fast membership testing, removing duplicates from a sequence,
399 and computing mathematical operations such as intersection, union, difference,
400 and symmetric difference.
401
402 For set elements, the same immutability rules apply as for dictionary keys. Note
403 that numeric types obey the normal rules for numeric comparison: if two numbers
404 compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a
405 set.
406
407 There are currently two intrinsic set types:
408
409 Sets
410 .. index:: object: set
411
412 These represent a mutable set. They are created by the built-in :func:`set`
413 constructor and can be modified afterwards by several methods, such as
Serhiy Storchakaad16b722013-10-09 14:02:14 +0300414 :meth:`~set.add`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000415
416 Frozen sets
417 .. index:: object: frozenset
418
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000419 These represent an immutable set. They are created by the built-in
420 :func:`frozenset` constructor. As a frozenset is immutable and
421 :term:`hashable`, it can be used again as an element of another set, or as
422 a dictionary key.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000423
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424Mappings
425 .. index::
426 builtin: len
427 single: subscription
428 object: mapping
429
430 These represent finite sets of objects indexed by arbitrary index sets. The
431 subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping
432 ``a``; this can be used in expressions and as the target of assignments or
433 :keyword:`del` statements. The built-in function :func:`len` returns the number
434 of items in a mapping.
435
436 There is currently a single intrinsic mapping type:
437
438 Dictionaries
439 .. index:: object: dictionary
440
441 These represent finite sets of objects indexed by nearly arbitrary values. The
442 only types of values not acceptable as keys are values containing lists or
443 dictionaries or other mutable types that are compared by value rather than by
444 object identity, the reason being that the efficient implementation of
445 dictionaries requires a key's hash value to remain constant. Numeric types used
446 for keys obey the normal rules for numeric comparison: if two numbers compare
447 equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index
448 the same dictionary entry.
449
450 Dictionaries are mutable; they can be created by the ``{...}`` notation (see
451 section :ref:`dict`).
452
453 .. index::
454 module: dbm
455 module: gdbm
456 module: bsddb
457
458 The extension modules :mod:`dbm`, :mod:`gdbm`, and :mod:`bsddb` provide
459 additional examples of mapping types.
460
Georg Brandl8ec7f652007-08-15 14:28:01 +0000461Callable types
462 .. index::
463 object: callable
464 pair: function; call
465 single: invocation
466 pair: function; argument
467
468 These are the types to which the function call operation (see section
469 :ref:`calls`) can be applied:
470
471 User-defined functions
472 .. index::
473 pair: user-defined; function
474 object: function
475 object: user-defined function
476
477 A user-defined function object is created by a function definition (see
478 section :ref:`function`). It should be called with an argument list
479 containing the same number of items as the function's formal parameter
480 list.
481
482 Special attributes:
483
Georg Brandl44ea77b2013-03-28 13:28:44 +0100484 .. tabularcolumns:: |l|L|l|
485
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486 +-----------------------+-------------------------------+-----------+
487 | Attribute | Meaning | |
488 +=======================+===============================+===========+
Mark Dickinson383952d2014-02-01 16:32:40 +0000489 | :attr:`__doc__` | The function's documentation | Writable |
490 | :attr:`func_doc` | string, or ``None`` if | |
491 | | unavailable. | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000492 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000493 | :attr:`__name__` | The function's name. | Writable |
494 | :attr:`func_name` | | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495 +-----------------------+-------------------------------+-----------+
496 | :attr:`__module__` | The name of the module the | Writable |
497 | | function was defined in, or | |
498 | | ``None`` if unavailable. | |
499 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000500 | :attr:`__defaults__` | A tuple containing default | Writable |
501 | :attr:`func_defaults` | argument values for those | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502 | | arguments that have defaults, | |
503 | | or ``None`` if no arguments | |
Mark Dickinson383952d2014-02-01 16:32:40 +0000504 | | have a default value. | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000505 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000506 | :attr:`__code__` | The code object representing | Writable |
507 | :attr:`func_code` | the compiled function body. | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000508 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000509 | :attr:`__globals__` | A reference to the dictionary | Read-only |
510 | :attr:`func_globals` | that holds the function's | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000511 | | global variables --- the | |
512 | | global namespace of the | |
513 | | module in which the function | |
514 | | was defined. | |
515 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000516 | :attr:`__dict__` | The namespace supporting | Writable |
517 | :attr:`func_dict` | arbitrary function | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000518 | | attributes. | |
519 +-----------------------+-------------------------------+-----------+
Mark Dickinson383952d2014-02-01 16:32:40 +0000520 | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only |
521 | :attr:`func_closure` | that contain bindings for the | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000522 | | function's free variables. | |
523 +-----------------------+-------------------------------+-----------+
524
525 Most of the attributes labelled "Writable" check the type of the assigned value.
526
527 .. versionchanged:: 2.4
528 ``func_name`` is now writable.
529
Mark Dickinson383952d2014-02-01 16:32:40 +0000530 .. versionchanged:: 2.6
531 The double-underscore attributes ``__closure__``, ``__code__``,
532 ``__defaults__``, and ``__globals__`` were introduced as aliases for
533 the corresponding ``func_*`` attributes for forwards compatibility
534 with Python 3.
535
Georg Brandl8ec7f652007-08-15 14:28:01 +0000536 Function objects also support getting and setting arbitrary attributes, which
537 can be used, for example, to attach metadata to functions. Regular attribute
538 dot-notation is used to get and set such attributes. *Note that the current
539 implementation only supports function attributes on user-defined functions.
540 Function attributes on built-in functions may be supported in the future.*
541
542 Additional information about a function's definition can be retrieved from its
543 code object; see the description of internal types below.
544
545 .. index::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546 single: __doc__ (function attribute)
547 single: __name__ (function attribute)
548 single: __module__ (function attribute)
549 single: __dict__ (function attribute)
Mark Dickinson383952d2014-02-01 16:32:40 +0000550 single: __defaults__ (function attribute)
551 single: __code__ (function attribute)
552 single: __globals__ (function attribute)
553 single: __closure__ (function attribute)
554 single: func_doc (function attribute)
555 single: func_name (function attribute)
556 single: func_dict (function attribute)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000557 single: func_defaults (function attribute)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000558 single: func_code (function attribute)
559 single: func_globals (function attribute)
Mark Dickinson383952d2014-02-01 16:32:40 +0000560 single: func_closure (function attribute)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561 pair: global; namespace
562
563 User-defined methods
564 .. index::
565 object: method
566 object: user-defined method
567 pair: user-defined; method
568
569 A user-defined method object combines a class, a class instance (or ``None``)
570 and any callable object (normally a user-defined function).
571
572 Special read-only attributes: :attr:`im_self` is the class instance object,
573 :attr:`im_func` is the function object; :attr:`im_class` is the class of
574 :attr:`im_self` for bound methods or the class that asked for the method for
575 unbound methods; :attr:`__doc__` is the method's documentation (same as
576 ``im_func.__doc__``); :attr:`__name__` is the method name (same as
577 ``im_func.__name__``); :attr:`__module__` is the name of the module the method
578 was defined in, or ``None`` if unavailable.
579
580 .. versionchanged:: 2.2
581 :attr:`im_self` used to refer to the class that defined the method.
582
Georg Brandl3fbe20c2008-03-21 19:20:21 +0000583 .. versionchanged:: 2.6
Ezio Melotti510ff542012-05-03 19:21:40 +0300584 For Python 3 forward-compatibility, :attr:`im_func` is also available as
Georg Brandl3fbe20c2008-03-21 19:20:21 +0000585 :attr:`__func__`, and :attr:`im_self` as :attr:`__self__`.
586
Georg Brandl8ec7f652007-08-15 14:28:01 +0000587 .. index::
588 single: __doc__ (method attribute)
589 single: __name__ (method attribute)
590 single: __module__ (method attribute)
591 single: im_func (method attribute)
592 single: im_self (method attribute)
593
594 Methods also support accessing (but not setting) the arbitrary function
595 attributes on the underlying function object.
596
597 User-defined method objects may be created when getting an attribute of a class
598 (perhaps via an instance of that class), if that attribute is a user-defined
599 function object, an unbound user-defined method object, or a class method
600 object. When the attribute is a user-defined method object, a new method object
601 is only created if the class from which it is being retrieved is the same as, or
602 a derived class of, the class stored in the original method object; otherwise,
603 the original method object is used as it is.
604
605 .. index::
606 single: im_class (method attribute)
607 single: im_func (method attribute)
608 single: im_self (method attribute)
609
610 When a user-defined method object is created by retrieving a user-defined
611 function object from a class, its :attr:`im_self` attribute is ``None``
612 and the method object is said to be unbound. When one is created by
613 retrieving a user-defined function object from a class via one of its
614 instances, its :attr:`im_self` attribute is the instance, and the method
615 object is said to be bound. In either case, the new method's
616 :attr:`im_class` attribute is the class from which the retrieval takes
617 place, and its :attr:`im_func` attribute is the original function object.
618
619 .. index:: single: im_func (method attribute)
620
621 When a user-defined method object is created by retrieving another method object
622 from a class or instance, the behaviour is the same as for a function object,
623 except that the :attr:`im_func` attribute of the new instance is not the
624 original method object but its :attr:`im_func` attribute.
625
626 .. index::
627 single: im_class (method attribute)
628 single: im_func (method attribute)
629 single: im_self (method attribute)
630
631 When a user-defined method object is created by retrieving a class method object
Georg Brandle7fb7002013-04-14 11:53:36 +0200632 from a class or instance, its :attr:`im_self` attribute is the class itself, and
633 its :attr:`im_func` attribute is the function object underlying the class method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000634
635 When an unbound user-defined method object is called, the underlying function
636 (:attr:`im_func`) is called, with the restriction that the first argument must
637 be an instance of the proper class (:attr:`im_class`) or of a derived class
638 thereof.
639
640 When a bound user-defined method object is called, the underlying function
641 (:attr:`im_func`) is called, inserting the class instance (:attr:`im_self`) in
642 front of the argument list. For instance, when :class:`C` is a class which
643 contains a definition for a function :meth:`f`, and ``x`` is an instance of
644 :class:`C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.
645
646 When a user-defined method object is derived from a class method object, the
647 "class instance" stored in :attr:`im_self` will actually be the class itself, so
648 that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to calling ``f(C,1)``
649 where ``f`` is the underlying function.
650
651 Note that the transformation from function object to (unbound or bound) method
652 object happens each time the attribute is retrieved from the class or instance.
653 In some cases, a fruitful optimization is to assign the attribute to a local
654 variable and call that local variable. Also notice that this transformation only
655 happens for user-defined functions; other callable objects (and all non-callable
656 objects) are retrieved without transformation. It is also important to note
657 that user-defined functions which are attributes of a class instance are not
658 converted to bound methods; this *only* happens when the function is an
659 attribute of the class.
660
661 Generator functions
662 .. index::
663 single: generator; function
664 single: generator; iterator
665
666 A function or method which uses the :keyword:`yield` statement (see section
667 :ref:`yield`) is called a :dfn:`generator
668 function`. Such a function, when called, always returns an iterator object
669 which can be used to execute the body of the function: calling the iterator's
Serhiy Storchakaad16b722013-10-09 14:02:14 +0300670 :meth:`~iterator.next` method will cause the function to execute until
671 it provides a value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000672 using the :keyword:`yield` statement. When the function executes a
673 :keyword:`return` statement or falls off the end, a :exc:`StopIteration`
674 exception is raised and the iterator will have reached the end of the set of
675 values to be returned.
676
677 Built-in functions
678 .. index::
679 object: built-in function
680 object: function
681 pair: C; language
682
683 A built-in function object is a wrapper around a C function. Examples of
684 built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
685 standard built-in module). The number and type of the arguments are
686 determined by the C function. Special read-only attributes:
687 :attr:`__doc__` is the function's documentation string, or ``None`` if
688 unavailable; :attr:`__name__` is the function's name; :attr:`__self__` is
689 set to ``None`` (but see the next item); :attr:`__module__` is the name of
690 the module the function was defined in or ``None`` if unavailable.
691
692 Built-in methods
693 .. index::
694 object: built-in method
695 object: method
696 pair: built-in; method
697
698 This is really a different disguise of a built-in function, this time containing
699 an object passed to the C function as an implicit extra argument. An example of
700 a built-in method is ``alist.append()``, assuming *alist* is a list object. In
701 this case, the special read-only attribute :attr:`__self__` is set to the object
Éric Araujo5c804ff2010-12-26 02:24:42 +0000702 denoted by *alist*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703
704 Class Types
705 Class types, or "new-style classes," are callable. These objects normally act
706 as factories for new instances of themselves, but variations are possible for
707 class types that override :meth:`__new__`. The arguments of the call are passed
708 to :meth:`__new__` and, in the typical case, to :meth:`__init__` to initialize
709 the new instance.
710
711 Classic Classes
712 .. index::
713 single: __init__() (object method)
714 object: class
715 object: class instance
716 object: instance
717 pair: class object; call
718
719 Class objects are described below. When a class object is called, a new class
720 instance (also described below) is created and returned. This implies a call to
721 the class's :meth:`__init__` method if it has one. Any arguments are passed on
722 to the :meth:`__init__` method. If there is no :meth:`__init__` method, the
723 class must be called without arguments.
724
725 Class instances
726 Class instances are described below. Class instances are callable only when the
727 class has a :meth:`__call__` method; ``x(arguments)`` is a shorthand for
728 ``x.__call__(arguments)``.
729
730Modules
731 .. index::
732 statement: import
733 object: module
734
735 Modules are imported by the :keyword:`import` statement (see section
736 :ref:`import`). A module object has a
737 namespace implemented by a dictionary object (this is the dictionary referenced
738 by the func_globals attribute of functions defined in the module). Attribute
739 references are translated to lookups in this dictionary, e.g., ``m.x`` is
740 equivalent to ``m.__dict__["x"]``. A module object does not contain the code
741 object used to initialize the module (since it isn't needed once the
742 initialization is done).
743
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744 Attribute assignment updates the module's namespace dictionary, e.g., ``m.x =
745 1`` is equivalent to ``m.__dict__["x"] = 1``.
746
747 .. index:: single: __dict__ (module attribute)
748
749 Special read-only attribute: :attr:`__dict__` is the module's namespace as a
750 dictionary object.
751
Benjamin Petersondc954242010-10-12 23:02:35 +0000752 .. impl-detail::
753
754 Because of the way CPython clears module dictionaries, the module
755 dictionary will be cleared when the module falls out of scope even if the
756 dictionary still has live references. To avoid this, copy the dictionary
757 or keep the module around while using its dictionary directly.
758
Georg Brandl8ec7f652007-08-15 14:28:01 +0000759 .. index::
760 single: __name__ (module attribute)
761 single: __doc__ (module attribute)
762 single: __file__ (module attribute)
763 pair: module; namespace
764
765 Predefined (writable) attributes: :attr:`__name__` is the module's name;
766 :attr:`__doc__` is the module's documentation string, or ``None`` if
767 unavailable; :attr:`__file__` is the pathname of the file from which the module
768 was loaded, if it was loaded from a file. The :attr:`__file__` attribute is not
769 present for C modules that are statically linked into the interpreter; for
770 extension modules loaded dynamically from a shared library, it is the pathname
771 of the shared library file.
772
773Classes
Nick Coghlana5107482008-08-04 12:40:59 +0000774 Both class types (new-style classes) and class objects (old-style/classic
775 classes) are typically created by class definitions (see section
776 :ref:`class`). A class has a namespace implemented by a dictionary object.
777 Class attribute references are translated to lookups in this dictionary, e.g.,
778 ``C.x`` is translated to ``C.__dict__["x"]`` (although for new-style classes
779 in particular there are a number of hooks which allow for other means of
780 locating attributes). When the attribute name is not found there, the
781 attribute search continues in the base classes. For old-style classes, the
782 search is depth-first, left-to-right in the order of occurrence in the base
783 class list. New-style classes use the more complex C3 method resolution
784 order which behaves correctly even in the presence of 'diamond'
785 inheritance structures where there are multiple inheritance paths
786 leading back to a common ancestor. Additional details on the C3 MRO used by
787 new-style classes can be found in the documentation accompanying the
788 2.3 release at http://www.python.org/download/releases/2.3/mro/.
789
790 .. XXX: Could we add that MRO doc as an appendix to the language ref?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
792 .. index::
793 object: class
794 object: class instance
795 object: instance
796 pair: class object; call
797 single: container
798 object: dictionary
799 pair: class; attribute
800
801 When a class attribute reference (for class :class:`C`, say) would yield a
802 user-defined function object or an unbound user-defined method object whose
803 associated class is either :class:`C` or one of its base classes, it is
804 transformed into an unbound user-defined method object whose :attr:`im_class`
805 attribute is :class:`C`. When it would yield a class method object, it is
Georg Brandle7fb7002013-04-14 11:53:36 +0200806 transformed into a bound user-defined method object whose
807 :attr:`im_self` attribute is :class:`C`. When it would yield a
Georg Brandl8ec7f652007-08-15 14:28:01 +0000808 static method object, it is transformed into the object wrapped by the static
809 method object. See section :ref:`descriptors` for another way in which
810 attributes retrieved from a class may differ from those actually contained in
Nick Coghlana5107482008-08-04 12:40:59 +0000811 its :attr:`__dict__` (note that only new-style classes support descriptors).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
813 .. index:: triple: class; attribute; assignment
814
815 Class attribute assignments update the class's dictionary, never the dictionary
816 of a base class.
817
818 .. index:: pair: class object; call
819
820 A class object can be called (see above) to yield a class instance (see below).
821
822 .. index::
823 single: __name__ (class attribute)
824 single: __module__ (class attribute)
825 single: __dict__ (class attribute)
826 single: __bases__ (class attribute)
827 single: __doc__ (class attribute)
828
829 Special attributes: :attr:`__name__` is the class name; :attr:`__module__` is
830 the module name in which the class was defined; :attr:`__dict__` is the
Serhiy Storchakaad16b722013-10-09 14:02:14 +0300831 dictionary containing the class's namespace; :attr:`~class.__bases__` is a
832 tuple (possibly empty or a singleton) containing the base classes, in the
833 order of their occurrence in the base class list; :attr:`__doc__` is the
834 class's documentation string, or None if undefined.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835
836Class instances
837 .. index::
838 object: class instance
839 object: instance
840 pair: class; instance
841 pair: class instance; attribute
842
843 A class instance is created by calling a class object (see above). A class
844 instance has a namespace implemented as a dictionary which is the first place in
845 which attribute references are searched. When an attribute is not found there,
846 and the instance's class has an attribute by that name, the search continues
847 with the class attributes. If a class attribute is found that is a user-defined
848 function object or an unbound user-defined method object whose associated class
849 is the class (call it :class:`C`) of the instance for which the attribute
850 reference was initiated or one of its bases, it is transformed into a bound
851 user-defined method object whose :attr:`im_class` attribute is :class:`C` and
852 whose :attr:`im_self` attribute is the instance. Static method and class method
853 objects are also transformed, as if they had been retrieved from class
854 :class:`C`; see above under "Classes". See section :ref:`descriptors` for
855 another way in which attributes of a class retrieved via its instances may
856 differ from the objects actually stored in the class's :attr:`__dict__`. If no
857 class attribute is found, and the object's class has a :meth:`__getattr__`
858 method, that is called to satisfy the lookup.
859
860 .. index:: triple: class instance; attribute; assignment
861
862 Attribute assignments and deletions update the instance's dictionary, never a
863 class's dictionary. If the class has a :meth:`__setattr__` or
864 :meth:`__delattr__` method, this is called instead of updating the instance
865 dictionary directly.
866
867 .. index::
868 object: numeric
869 object: sequence
870 object: mapping
871
872 Class instances can pretend to be numbers, sequences, or mappings if they have
873 methods with certain special names. See section :ref:`specialnames`.
874
875 .. index::
876 single: __dict__ (instance attribute)
877 single: __class__ (instance attribute)
878
Serhiy Storchakaad16b722013-10-09 14:02:14 +0300879 Special attributes: :attr:`~object.__dict__` is the attribute dictionary;
880 :attr:`~instance.__class__` is the instance's class.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000881
882Files
883 .. index::
884 object: file
885 builtin: open
886 single: popen() (in module os)
887 single: makefile() (socket method)
888 single: sys.stdin
889 single: sys.stdout
890 single: sys.stderr
891 single: stdio
892 single: stdin (in module sys)
893 single: stdout (in module sys)
894 single: stderr (in module sys)
895
896 A file object represents an open file. File objects are created by the
897 :func:`open` built-in function, and also by :func:`os.popen`,
898 :func:`os.fdopen`, and the :meth:`makefile` method of socket objects (and
899 perhaps by other functions or methods provided by extension modules). The
900 objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are initialized to
901 file objects corresponding to the interpreter's standard input, output and
902 error streams. See :ref:`bltin-file-objects` for complete documentation of
903 file objects.
904
905Internal types
906 .. index::
907 single: internal type
908 single: types, internal
909
910 A few types used internally by the interpreter are exposed to the user. Their
911 definitions may change with future versions of the interpreter, but they are
912 mentioned here for completeness.
913
914 Code objects
915 .. index::
916 single: bytecode
917 object: code
918
Georg Brandl63fa1682007-10-21 10:24:20 +0000919 Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000920 The difference between a code object and a function object is that the function
921 object contains an explicit reference to the function's globals (the module in
922 which it was defined), while a code object contains no context; also the default
923 argument values are stored in the function object, not in the code object
924 (because they represent values calculated at run-time). Unlike function
925 objects, code objects are immutable and contain no references (directly or
926 indirectly) to mutable objects.
927
Senthil Kumaranfca48ef2010-10-02 03:29:31 +0000928 .. index::
929 single: co_argcount (code object attribute)
930 single: co_code (code object attribute)
931 single: co_consts (code object attribute)
932 single: co_filename (code object attribute)
933 single: co_firstlineno (code object attribute)
934 single: co_flags (code object attribute)
935 single: co_lnotab (code object attribute)
936 single: co_name (code object attribute)
937 single: co_names (code object attribute)
938 single: co_nlocals (code object attribute)
939 single: co_stacksize (code object attribute)
940 single: co_varnames (code object attribute)
941 single: co_cellvars (code object attribute)
942 single: co_freevars (code object attribute)
943
Georg Brandl8ec7f652007-08-15 14:28:01 +0000944 Special read-only attributes: :attr:`co_name` gives the function name;
945 :attr:`co_argcount` is the number of positional arguments (including arguments
946 with default values); :attr:`co_nlocals` is the number of local variables used
947 by the function (including arguments); :attr:`co_varnames` is a tuple containing
948 the names of the local variables (starting with the argument names);
949 :attr:`co_cellvars` is a tuple containing the names of local variables that are
950 referenced by nested functions; :attr:`co_freevars` is a tuple containing the
951 names of free variables; :attr:`co_code` is a string representing the sequence
952 of bytecode instructions; :attr:`co_consts` is a tuple containing the literals
953 used by the bytecode; :attr:`co_names` is a tuple containing the names used by
954 the bytecode; :attr:`co_filename` is the filename from which the code was
955 compiled; :attr:`co_firstlineno` is the first line number of the function;
Georg Brandl63fa1682007-10-21 10:24:20 +0000956 :attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957 line numbers (for details see the source code of the interpreter);
958 :attr:`co_stacksize` is the required stack size (including local variables);
959 :attr:`co_flags` is an integer encoding a number of flags for the interpreter.
960
Georg Brandl8ec7f652007-08-15 14:28:01 +0000961 .. index:: object: generator
962
963 The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is set if
964 the function uses the ``*arguments`` syntax to accept an arbitrary number of
965 positional arguments; bit ``0x08`` is set if the function uses the
966 ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set
967 if the function is a generator.
968
969 Future feature declarations (``from __future__ import division``) also use bits
970 in :attr:`co_flags` to indicate whether a code object was compiled with a
971 particular feature enabled: bit ``0x2000`` is set if the function was compiled
972 with future division enabled; bits ``0x10`` and ``0x1000`` were used in earlier
973 versions of Python.
974
975 Other bits in :attr:`co_flags` are reserved for internal use.
976
977 .. index:: single: documentation string
978
979 If a code object represents a function, the first item in :attr:`co_consts` is
980 the documentation string of the function, or ``None`` if undefined.
981
Georg Brandl86158fc2009-09-01 08:00:47 +0000982 .. _frame-objects:
983
Georg Brandl8ec7f652007-08-15 14:28:01 +0000984 Frame objects
985 .. index:: object: frame
986
987 Frame objects represent execution frames. They may occur in traceback objects
988 (see below).
989
990 .. index::
991 single: f_back (frame attribute)
992 single: f_code (frame attribute)
993 single: f_globals (frame attribute)
994 single: f_locals (frame attribute)
995 single: f_lasti (frame attribute)
996 single: f_builtins (frame attribute)
997 single: f_restricted (frame attribute)
998
999 Special read-only attributes: :attr:`f_back` is to the previous stack frame
1000 (towards the caller), or ``None`` if this is the bottom stack frame;
1001 :attr:`f_code` is the code object being executed in this frame; :attr:`f_locals`
1002 is the dictionary used to look up local variables; :attr:`f_globals` is used for
1003 global variables; :attr:`f_builtins` is used for built-in (intrinsic) names;
1004 :attr:`f_restricted` is a flag indicating whether the function is executing in
1005 restricted execution mode; :attr:`f_lasti` gives the precise instruction (this
1006 is an index into the bytecode string of the code object).
1007
1008 .. index::
1009 single: f_trace (frame attribute)
1010 single: f_exc_type (frame attribute)
1011 single: f_exc_value (frame attribute)
1012 single: f_exc_traceback (frame attribute)
1013 single: f_lineno (frame attribute)
1014
1015 Special writable attributes: :attr:`f_trace`, if not ``None``, is a function
1016 called at the start of each source code line (this is used by the debugger);
1017 :attr:`f_exc_type`, :attr:`f_exc_value`, :attr:`f_exc_traceback` represent the
1018 last exception raised in the parent frame provided another exception was ever
1019 raised in the current frame (in all other cases they are None); :attr:`f_lineno`
1020 is the current line number of the frame --- writing to this from within a trace
1021 function jumps to the given line (only for the bottom-most frame). A debugger
1022 can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
1023
1024 Traceback objects
1025 .. index::
1026 object: traceback
1027 pair: stack; trace
1028 pair: exception; handler
1029 pair: execution; stack
1030 single: exc_info (in module sys)
1031 single: exc_traceback (in module sys)
1032 single: last_traceback (in module sys)
1033 single: sys.exc_info
1034 single: sys.exc_traceback
1035 single: sys.last_traceback
1036
1037 Traceback objects represent a stack trace of an exception. A traceback object
1038 is created when an exception occurs. When the search for an exception handler
1039 unwinds the execution stack, at each unwound level a traceback object is
1040 inserted in front of the current traceback. When an exception handler is
1041 entered, the stack trace is made available to the program. (See section
1042 :ref:`try`.) It is accessible as ``sys.exc_traceback``,
1043 and also as the third item of the tuple returned by ``sys.exc_info()``. The
1044 latter is the preferred interface, since it works correctly when the program is
1045 using multiple threads. When the program contains no suitable handler, the stack
1046 trace is written (nicely formatted) to the standard error stream; if the
1047 interpreter is interactive, it is also made available to the user as
1048 ``sys.last_traceback``.
1049
1050 .. index::
1051 single: tb_next (traceback attribute)
1052 single: tb_frame (traceback attribute)
1053 single: tb_lineno (traceback attribute)
1054 single: tb_lasti (traceback attribute)
1055 statement: try
1056
1057 Special read-only attributes: :attr:`tb_next` is the next level in the stack
1058 trace (towards the frame where the exception occurred), or ``None`` if there is
1059 no next level; :attr:`tb_frame` points to the execution frame of the current
1060 level; :attr:`tb_lineno` gives the line number where the exception occurred;
1061 :attr:`tb_lasti` indicates the precise instruction. The line number and last
1062 instruction in the traceback may differ from the line number of its frame object
1063 if the exception occurred in a :keyword:`try` statement with no matching except
1064 clause or with a finally clause.
1065
1066 Slice objects
1067 .. index:: builtin: slice
1068
1069 Slice objects are used to represent slices when *extended slice syntax* is used.
1070 This is a slice using two colons, or multiple slices or ellipses separated by
1071 commas, e.g., ``a[i:j:step]``, ``a[i:j, k:l]``, or ``a[..., i:j]``. They are
1072 also created by the built-in :func:`slice` function.
1073
1074 .. index::
1075 single: start (slice object attribute)
1076 single: stop (slice object attribute)
1077 single: step (slice object attribute)
1078
Serhiy Storchakaad16b722013-10-09 14:02:14 +03001079 Special read-only attributes: :attr:`~slice.start` is the lower bound;
1080 :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step
1081 value; each is ``None`` if omitted. These attributes can have any type.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
1083 Slice objects support one method:
1084
1085
1086 .. method:: slice.indices(self, length)
1087
1088 This method takes a single integer argument *length* and computes information
1089 about the extended slice that the slice object would describe if applied to a
1090 sequence of *length* items. It returns a tuple of three integers; respectively
1091 these are the *start* and *stop* indices and the *step* or stride length of the
1092 slice. Missing or out-of-bounds indices are handled in a manner consistent with
1093 regular slices.
1094
1095 .. versionadded:: 2.3
1096
1097 Static method objects
1098 Static method objects provide a way of defeating the transformation of function
1099 objects to method objects described above. A static method object is a wrapper
1100 around any other object, usually a user-defined method object. When a static
1101 method object is retrieved from a class or a class instance, the object actually
1102 returned is the wrapped object, which is not subject to any further
1103 transformation. Static method objects are not themselves callable, although the
1104 objects they wrap usually are. Static method objects are created by the built-in
1105 :func:`staticmethod` constructor.
1106
1107 Class method objects
1108 A class method object, like a static method object, is a wrapper around another
1109 object that alters the way in which that object is retrieved from classes and
1110 class instances. The behaviour of class method objects upon such retrieval is
1111 described above, under "User-defined methods". Class method objects are created
1112 by the built-in :func:`classmethod` constructor.
1113
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114
Georg Brandla7395032007-10-21 12:15:05 +00001115.. _newstyle:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001116
1117New-style and classic classes
1118=============================
1119
Nick Coghlana5107482008-08-04 12:40:59 +00001120Classes and instances come in two flavors: old-style (or classic) and new-style.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001121
1122Up to Python 2.1, old-style classes were the only flavour available to the user.
1123The concept of (old-style) class is unrelated to the concept of type: if *x* is
1124an instance of an old-style class, then ``x.__class__`` designates the class of
1125*x*, but ``type(x)`` is always ``<type 'instance'>``. This reflects the fact
1126that all old-style instances, independently of their class, are implemented with
1127a single built-in type, called ``instance``.
1128
1129New-style classes were introduced in Python 2.2 to unify classes and types. A
Georg Brandl63cdb862008-02-03 12:29:00 +00001130new-style class is neither more nor less than a user-defined type. If *x* is an
Nick Coghlana5107482008-08-04 12:40:59 +00001131instance of a new-style class, then ``type(x)`` is typically the same as
1132``x.__class__`` (although this is not guaranteed - a new-style class instance is
1133permitted to override the value returned for ``x.__class__``).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
1135The major motivation for introducing new-style classes is to provide a unified
Nick Coghlana5107482008-08-04 12:40:59 +00001136object model with a full meta-model. It also has a number of practical
Georg Brandl8ec7f652007-08-15 14:28:01 +00001137benefits, like the ability to subclass most built-in types, or the introduction
1138of "descriptors", which enable computed properties.
1139
1140For compatibility reasons, classes are still old-style by default. New-style
1141classes are created by specifying another new-style class (i.e. a type) as a
1142parent class, or the "top-level type" :class:`object` if no other parent is
1143needed. The behaviour of new-style classes differs from that of old-style
1144classes in a number of important details in addition to what :func:`type`
1145returns. Some of these changes are fundamental to the new object model, like
1146the way special methods are invoked. Others are "fixes" that could not be
1147implemented before for compatibility concerns, like the method resolution order
1148in case of multiple inheritance.
1149
Nick Coghlana5107482008-08-04 12:40:59 +00001150While this manual aims to provide comprehensive coverage of Python's class
1151mechanics, it may still be lacking in some areas when it comes to its coverage
1152of new-style classes. Please see http://www.python.org/doc/newstyle/ for
1153sources of additional information.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001154
1155.. index::
Georg Brandl62658332008-01-05 19:29:45 +00001156 single: class; new-style
1157 single: class; classic
1158 single: class; old-style
Georg Brandl8ec7f652007-08-15 14:28:01 +00001159
Ezio Melotti510ff542012-05-03 19:21:40 +03001160Old-style classes are removed in Python 3, leaving only the semantics of
Nick Coghlana5107482008-08-04 12:40:59 +00001161new-style classes.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001162
Georg Brandl8ec7f652007-08-15 14:28:01 +00001163
1164.. _specialnames:
1165
1166Special method names
1167====================
1168
1169.. index::
1170 pair: operator; overloading
1171 single: __getitem__() (mapping object method)
1172
1173A class can implement certain operations that are invoked by special syntax
1174(such as arithmetic operations or subscripting and slicing) by defining methods
1175with special names. This is Python's approach to :dfn:`operator overloading`,
1176allowing classes to define their own behavior with respect to language
1177operators. For instance, if a class defines a method named :meth:`__getitem__`,
Nick Coghlana5107482008-08-04 12:40:59 +00001178and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
1179to ``x.__getitem__(i)`` for old-style classes and ``type(x).__getitem__(x, i)``
1180for new-style classes. Except where mentioned, attempts to execute an
1181operation raise an exception when no appropriate method is defined (typically
1182:exc:`AttributeError` or :exc:`TypeError`).
Georg Brandl5768d572007-09-05 13:36:44 +00001183
Georg Brandl8ec7f652007-08-15 14:28:01 +00001184When implementing a class that emulates any built-in type, it is important that
1185the emulation only be implemented to the degree that it makes sense for the
1186object being modelled. For example, some sequences may work well with retrieval
1187of individual elements, but extracting a slice may not make sense. (One example
Serhiy Storchakaad16b722013-10-09 14:02:14 +03001188of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document
1189Object Model.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001190
1191
1192.. _customization:
1193
1194Basic customization
1195-------------------
1196
Georg Brandl8ec7f652007-08-15 14:28:01 +00001197.. method:: object.__new__(cls[, ...])
1198
Georg Brandl3fc42262008-12-05 08:06:57 +00001199 .. index:: pair: subclassing; immutable types
1200
Georg Brandl8ec7f652007-08-15 14:28:01 +00001201 Called to create a new instance of class *cls*. :meth:`__new__` is a static
1202 method (special-cased so you need not declare it as such) that takes the class
1203 of which an instance was requested as its first argument. The remaining
1204 arguments are those passed to the object constructor expression (the call to the
1205 class). The return value of :meth:`__new__` should be the new object instance
1206 (usually an instance of *cls*).
1207
1208 Typical implementations create a new instance of the class by invoking the
1209 superclass's :meth:`__new__` method using ``super(currentclass,
1210 cls).__new__(cls[, ...])`` with appropriate arguments and then modifying the
1211 newly-created instance as necessary before returning it.
1212
1213 If :meth:`__new__` returns an instance of *cls*, then the new instance's
1214 :meth:`__init__` method will be invoked like ``__init__(self[, ...])``, where
1215 *self* is the new instance and the remaining arguments are the same as were
1216 passed to :meth:`__new__`.
1217
1218 If :meth:`__new__` does not return an instance of *cls*, then the new instance's
1219 :meth:`__init__` method will not be invoked.
1220
1221 :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
Georg Brandl3ccb49a2008-01-07 19:17:10 +00001222 int, str, or tuple) to customize instance creation. It is also commonly
1223 overridden in custom metaclasses in order to customize class creation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001224
1225
1226.. method:: object.__init__(self[, ...])
1227
1228 .. index:: pair: class; constructor
1229
1230 Called when the instance is created. The arguments are those passed to the
1231 class constructor expression. If a base class has an :meth:`__init__` method,
1232 the derived class's :meth:`__init__` method, if any, must explicitly call it to
1233 ensure proper initialization of the base class part of the instance; for
1234 example: ``BaseClass.__init__(self, [args...])``. As a special constraint on
1235 constructors, no value may be returned; doing so will cause a :exc:`TypeError`
1236 to be raised at runtime.
1237
1238
1239.. method:: object.__del__(self)
1240
1241 .. index::
1242 single: destructor
1243 statement: del
1244
1245 Called when the instance is about to be destroyed. This is also called a
1246 destructor. If a base class has a :meth:`__del__` method, the derived class's
1247 :meth:`__del__` method, if any, must explicitly call it to ensure proper
1248 deletion of the base class part of the instance. Note that it is possible
1249 (though not recommended!) for the :meth:`__del__` method to postpone destruction
1250 of the instance by creating a new reference to it. It may then be called at a
1251 later time when this new reference is deleted. It is not guaranteed that
1252 :meth:`__del__` methods are called for objects that still exist when the
1253 interpreter exits.
1254
1255 .. note::
1256
1257 ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
1258 the reference count for ``x`` by one, and the latter is only called when
1259 ``x``'s reference count reaches zero. Some common situations that may
1260 prevent the reference count of an object from going to zero include:
1261 circular references between objects (e.g., a doubly-linked list or a tree
1262 data structure with parent and child pointers); a reference to the object
1263 on the stack frame of a function that caught an exception (the traceback
1264 stored in ``sys.exc_traceback`` keeps the stack frame alive); or a
1265 reference to the object on the stack frame that raised an unhandled
1266 exception in interactive mode (the traceback stored in
1267 ``sys.last_traceback`` keeps the stack frame alive). The first situation
1268 can only be remedied by explicitly breaking the cycles; the latter two
1269 situations can be resolved by storing ``None`` in ``sys.exc_traceback`` or
1270 ``sys.last_traceback``. Circular references which are garbage are
1271 detected when the option cycle detector is enabled (it's on by default),
1272 but can only be cleaned up if there are no Python-level :meth:`__del__`
1273 methods involved. Refer to the documentation for the :mod:`gc` module for
1274 more information about how :meth:`__del__` methods are handled by the
1275 cycle detector, particularly the description of the ``garbage`` value.
1276
1277 .. warning::
1278
1279 Due to the precarious circumstances under which :meth:`__del__` methods are
1280 invoked, exceptions that occur during their execution are ignored, and a warning
1281 is printed to ``sys.stderr`` instead. Also, when :meth:`__del__` is invoked in
1282 response to a module being deleted (e.g., when execution of the program is
1283 done), other globals referenced by the :meth:`__del__` method may already have
Brett Cannon5b0d5532009-01-29 00:54:11 +00001284 been deleted or in the process of being torn down (e.g. the import
1285 machinery shutting down). For this reason, :meth:`__del__` methods
1286 should do the absolute
Georg Brandl8ec7f652007-08-15 14:28:01 +00001287 minimum needed to maintain external invariants. Starting with version 1.5,
1288 Python guarantees that globals whose name begins with a single underscore are
1289 deleted from their module before other globals are deleted; if no other
1290 references to such globals exist, this may help in assuring that imported
1291 modules are still available at the time when the :meth:`__del__` method is
1292 called.
1293
Barry Warsaw1e13eb02012-02-20 20:42:21 -05001294 See also the :option:`-R` command-line option.
1295
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296
1297.. method:: object.__repr__(self)
1298
1299 .. index:: builtin: repr
1300
1301 Called by the :func:`repr` built-in function and by string conversions (reverse
1302 quotes) to compute the "official" string representation of an object. If at all
1303 possible, this should look like a valid Python expression that could be used to
1304 recreate an object with the same value (given an appropriate environment). If
1305 this is not possible, a string of the form ``<...some useful description...>``
1306 should be returned. The return value must be a string object. If a class
1307 defines :meth:`__repr__` but not :meth:`__str__`, then :meth:`__repr__` is also
1308 used when an "informal" string representation of instances of that class is
1309 required.
1310
1311 .. index::
1312 pair: string; conversion
1313 pair: reverse; quotes
1314 pair: backward; quotes
1315 single: back-quotes
1316
1317 This is typically used for debugging, so it is important that the representation
1318 is information-rich and unambiguous.
1319
1320
1321.. method:: object.__str__(self)
1322
1323 .. index::
1324 builtin: str
1325 statement: print
1326
1327 Called by the :func:`str` built-in function and by the :keyword:`print`
1328 statement to compute the "informal" string representation of an object. This
1329 differs from :meth:`__repr__` in that it does not have to be a valid Python
1330 expression: a more convenient or concise representation may be used instead.
1331 The return value must be a string object.
1332
1333
1334.. method:: object.__lt__(self, other)
1335 object.__le__(self, other)
1336 object.__eq__(self, other)
1337 object.__ne__(self, other)
1338 object.__gt__(self, other)
1339 object.__ge__(self, other)
1340
1341 .. versionadded:: 2.1
1342
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001343 .. index::
1344 single: comparisons
1345
Georg Brandl8ec7f652007-08-15 14:28:01 +00001346 These are the so-called "rich comparison" methods, and are called for comparison
1347 operators in preference to :meth:`__cmp__` below. The correspondence between
1348 operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
1349 ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and
1350 ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls
1351 ``x.__ge__(y)``.
1352
1353 A rich comparison method may return the singleton ``NotImplemented`` if it does
1354 not implement the operation for a given pair of arguments. By convention,
1355 ``False`` and ``True`` are returned for a successful comparison. However, these
1356 methods can return any value, so if the comparison operator is used in a Boolean
1357 context (e.g., in the condition of an ``if`` statement), Python will call
1358 :func:`bool` on the value to determine if the result is true or false.
1359
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001360 There are no implied relationships among the comparison operators. The truth
1361 of ``x==y`` does not imply that ``x!=y`` is false. Accordingly, when
1362 defining :meth:`__eq__`, one should also define :meth:`__ne__` so that the
1363 operators will behave as expected. See the paragraph on :meth:`__hash__` for
1364 some important notes on creating :term:`hashable` objects which support
1365 custom comparison operations and are usable as dictionary keys.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001366
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001367 There are no swapped-argument versions of these methods (to be used when the
1368 left argument does not support the operation but the right argument does);
1369 rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001370 :meth:`__le__` and :meth:`__ge__` are each other's reflection, and
1371 :meth:`__eq__` and :meth:`__ne__` are their own reflection.
1372
1373 Arguments to rich comparison methods are never coerced.
1374
Raymond Hettinger351de802009-03-12 00:25:03 +00001375 To automatically generate ordering operations from a single root operation,
Raymond Hettinger06bc0b62010-04-04 22:24:03 +00001376 see :func:`functools.total_ordering`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001377
1378.. method:: object.__cmp__(self, other)
1379
1380 .. index::
1381 builtin: cmp
1382 single: comparisons
1383
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001384 Called by comparison operations if rich comparison (see above) is not
1385 defined. Should return a negative integer if ``self < other``, zero if
1386 ``self == other``, a positive integer if ``self > other``. If no
1387 :meth:`__cmp__`, :meth:`__eq__` or :meth:`__ne__` operation is defined, class
1388 instances are compared by object identity ("address"). See also the
1389 description of :meth:`__hash__` for some important notes on creating
1390 :term:`hashable` objects which support custom comparison operations and are
1391 usable as dictionary keys. (Note: the restriction that exceptions are not
1392 propagated by :meth:`__cmp__` has been removed since Python 1.5.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001393
1394
1395.. method:: object.__rcmp__(self, other)
1396
1397 .. versionchanged:: 2.1
1398 No longer supported.
1399
1400
1401.. method:: object.__hash__(self)
1402
1403 .. index::
1404 object: dictionary
1405 builtin: hash
1406
Benjamin Peterson233bb002008-11-17 22:05:19 +00001407 Called by built-in function :func:`hash` and for operations on members of
1408 hashed collections including :class:`set`, :class:`frozenset`, and
1409 :class:`dict`. :meth:`__hash__` should return an integer. The only required
1410 property is that objects which compare equal have the same hash value; it is
1411 advised to somehow mix together (e.g. using exclusive or) the hash values for
1412 the components of the object that also play a part in comparison of objects.
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001413
1414 If a class does not define a :meth:`__cmp__` or :meth:`__eq__` method it
1415 should not define a :meth:`__hash__` operation either; if it defines
1416 :meth:`__cmp__` or :meth:`__eq__` but not :meth:`__hash__`, its instances
Benjamin Peterson233bb002008-11-17 22:05:19 +00001417 will not be usable in hashed collections. If a class defines mutable objects
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001418 and implements a :meth:`__cmp__` or :meth:`__eq__` method, it should not
Benjamin Peterson233bb002008-11-17 22:05:19 +00001419 implement :meth:`__hash__`, since hashable collection implementations require
1420 that a object's hash value is immutable (if the object's hash value changes,
1421 it will be in the wrong hash bucket).
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001422
1423 User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods
Nick Coghlan82358692008-08-31 13:10:50 +00001424 by default; with them, all objects compare unequal (except with themselves)
1425 and ``x.__hash__()`` returns ``id(x)``.
1426
1427 Classes which inherit a :meth:`__hash__` method from a parent class but
1428 change the meaning of :meth:`__cmp__` or :meth:`__eq__` such that the hash
1429 value returned is no longer appropriate (e.g. by switching to a value-based
1430 concept of equality instead of the default identity based equality) can
Benjamin Peterson233bb002008-11-17 22:05:19 +00001431 explicitly flag themselves as being unhashable by setting ``__hash__ = None``
1432 in the class definition. Doing so means that not only will instances of the
1433 class raise an appropriate :exc:`TypeError` when a program attempts to
1434 retrieve their hash value, but they will also be correctly identified as
1435 unhashable when checking ``isinstance(obj, collections.Hashable)`` (unlike
1436 classes which define their own :meth:`__hash__` to explicitly raise
1437 :exc:`TypeError`).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001438
1439 .. versionchanged:: 2.5
Georg Brandl7c3e79f2007-11-02 20:06:17 +00001440 :meth:`__hash__` may now also return a long integer object; the 32-bit
1441 integer is then derived from the hash of that object.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001442
Nick Coghlan82358692008-08-31 13:10:50 +00001443 .. versionchanged:: 2.6
1444 :attr:`__hash__` may now be set to :const:`None` to explicitly flag
1445 instances of a class as unhashable.
1446
Georg Brandl8ec7f652007-08-15 14:28:01 +00001447
1448.. method:: object.__nonzero__(self)
1449
1450 .. index:: single: __len__() (mapping object method)
1451
Georg Brandl3259ef32009-03-15 21:37:16 +00001452 Called to implement truth value testing and the built-in operation ``bool()``;
Georg Brandl8ec7f652007-08-15 14:28:01 +00001453 should return ``False`` or ``True``, or their integer equivalents ``0`` or
Georg Brandl3259ef32009-03-15 21:37:16 +00001454 ``1``. When this method is not defined, :meth:`__len__` is called, if it is
1455 defined, and the object is considered true if its result is nonzero.
1456 If a class defines neither :meth:`__len__` nor :meth:`__nonzero__`, all its
1457 instances are considered true.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001458
1459
1460.. method:: object.__unicode__(self)
1461
1462 .. index:: builtin: unicode
1463
Georg Brandld7d4fd72009-07-26 14:37:28 +00001464 Called to implement :func:`unicode` built-in; should return a Unicode object.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001465 When this method is not defined, string conversion is attempted, and the result
1466 of string conversion is converted to Unicode using the system default encoding.
1467
1468
1469.. _attribute-access:
1470
1471Customizing attribute access
1472----------------------------
1473
1474The following methods can be defined to customize the meaning of attribute
1475access (use of, assignment to, or deletion of ``x.name``) for class instances.
1476
1477
1478.. method:: object.__getattr__(self, name)
1479
1480 Called when an attribute lookup has not found the attribute in the usual places
1481 (i.e. it is not an instance attribute nor is it found in the class tree for
1482 ``self``). ``name`` is the attribute name. This method should return the
1483 (computed) attribute value or raise an :exc:`AttributeError` exception.
1484
1485 .. index:: single: __setattr__() (object method)
1486
1487 Note that if the attribute is found through the normal mechanism,
1488 :meth:`__getattr__` is not called. (This is an intentional asymmetry between
1489 :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
Georg Brandlc1768142008-08-30 09:52:44 +00001490 reasons and because otherwise :meth:`__getattr__` would have no way to access
Georg Brandl8ec7f652007-08-15 14:28:01 +00001491 other attributes of the instance. Note that at least for instance variables,
1492 you can fake total control by not inserting any values in the instance attribute
1493 dictionary (but instead inserting them in another object). See the
1494 :meth:`__getattribute__` method below for a way to actually get total control in
1495 new-style classes.
1496
1497
1498.. method:: object.__setattr__(self, name, value)
1499
1500 Called when an attribute assignment is attempted. This is called instead of the
1501 normal mechanism (i.e. store the value in the instance dictionary). *name* is
1502 the attribute name, *value* is the value to be assigned to it.
1503
1504 .. index:: single: __dict__ (instance attribute)
1505
1506 If :meth:`__setattr__` wants to assign to an instance attribute, it should not
1507 simply execute ``self.name = value`` --- this would cause a recursive call to
1508 itself. Instead, it should insert the value in the dictionary of instance
1509 attributes, e.g., ``self.__dict__[name] = value``. For new-style classes,
1510 rather than accessing the instance dictionary, it should call the base class
1511 method with the same name, for example, ``object.__setattr__(self, name,
1512 value)``.
1513
1514
1515.. method:: object.__delattr__(self, name)
1516
1517 Like :meth:`__setattr__` but for attribute deletion instead of assignment. This
1518 should only be implemented if ``del obj.name`` is meaningful for the object.
1519
1520
1521.. _new-style-attribute-access:
1522
1523More attribute access for new-style classes
1524^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1525
1526The following methods only apply to new-style classes.
1527
1528
1529.. method:: object.__getattribute__(self, name)
1530
1531 Called unconditionally to implement attribute accesses for instances of the
1532 class. If the class also defines :meth:`__getattr__`, the latter will not be
1533 called unless :meth:`__getattribute__` either calls it explicitly or raises an
1534 :exc:`AttributeError`. This method should return the (computed) attribute value
1535 or raise an :exc:`AttributeError` exception. In order to avoid infinite
1536 recursion in this method, its implementation should always call the base class
1537 method with the same name to access any attributes it needs, for example,
1538 ``object.__getattribute__(self, name)``.
1539
Nick Coghlana5107482008-08-04 12:40:59 +00001540 .. note::
1541
1542 This method may still be bypassed when looking up special methods as the
Georg Brandld7d4fd72009-07-26 14:37:28 +00001543 result of implicit invocation via language syntax or built-in functions.
Nick Coghlana5107482008-08-04 12:40:59 +00001544 See :ref:`new-style-special-lookup`.
1545
Georg Brandl8ec7f652007-08-15 14:28:01 +00001546
1547.. _descriptors:
1548
1549Implementing Descriptors
1550^^^^^^^^^^^^^^^^^^^^^^^^
1551
1552The following methods only apply when an instance of the class containing the
Raymond Hettinger1fd26522011-03-22 17:51:57 -07001553method (a so-called *descriptor* class) appears in an *owner* class (the
1554descriptor must be in either the owner's class dictionary or in the class
1555dictionary for one of its parents). In the examples below, "the attribute"
1556refers to the attribute whose name is the key of the property in the owner
1557class' :attr:`__dict__`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001558
1559
1560.. method:: object.__get__(self, instance, owner)
1561
1562 Called to get the attribute of the owner class (class attribute access) or of an
1563 instance of that class (instance attribute access). *owner* is always the owner
1564 class, while *instance* is the instance that the attribute was accessed through,
1565 or ``None`` when the attribute is accessed through the *owner*. This method
1566 should return the (computed) attribute value or raise an :exc:`AttributeError`
1567 exception.
1568
1569
1570.. method:: object.__set__(self, instance, value)
1571
1572 Called to set the attribute on an instance *instance* of the owner class to a
1573 new value, *value*.
1574
1575
1576.. method:: object.__delete__(self, instance)
1577
1578 Called to delete the attribute on an instance *instance* of the owner class.
1579
1580
1581.. _descriptor-invocation:
1582
1583Invoking Descriptors
1584^^^^^^^^^^^^^^^^^^^^
1585
1586In general, a descriptor is an object attribute with "binding behavior", one
1587whose attribute access has been overridden by methods in the descriptor
1588protocol: :meth:`__get__`, :meth:`__set__`, and :meth:`__delete__`. If any of
1589those methods are defined for an object, it is said to be a descriptor.
1590
1591The default behavior for attribute access is to get, set, or delete the
1592attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain
1593starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
1594continuing through the base classes of ``type(a)`` excluding metaclasses.
1595
1596However, if the looked-up value is an object defining one of the descriptor
1597methods, then Python may override the default behavior and invoke the descriptor
1598method instead. Where this occurs in the precedence chain depends on which
1599descriptor methods were defined and how they were called. Note that descriptors
1600are only invoked for new style objects or classes (ones that subclass
1601:class:`object()` or :class:`type()`).
1602
1603The starting point for descriptor invocation is a binding, ``a.x``. How the
1604arguments are assembled depends on ``a``:
1605
1606Direct Call
1607 The simplest and least common call is when user code directly invokes a
1608 descriptor method: ``x.__get__(a)``.
1609
1610Instance Binding
1611 If binding to a new-style object instance, ``a.x`` is transformed into the call:
1612 ``type(a).__dict__['x'].__get__(a, type(a))``.
1613
1614Class Binding
1615 If binding to a new-style class, ``A.x`` is transformed into the call:
1616 ``A.__dict__['x'].__get__(None, A)``.
1617
1618Super Binding
1619 If ``a`` is an instance of :class:`super`, then the binding ``super(B,
1620 obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A``
1621 immediately preceding ``B`` and then invokes the descriptor with the call:
Raymond Hettingerb76f6202011-03-22 15:28:45 -07001622 ``A.__dict__['m'].__get__(obj, obj.__class__)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001623
1624For instance bindings, the precedence of descriptor invocation depends on the
Benjamin Peterson9179dab2010-01-18 23:07:56 +00001625which descriptor methods are defined. A descriptor can define any combination
1626of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not
1627define :meth:`__get__`, then accessing the attribute will return the descriptor
1628object itself unless there is a value in the object's instance dictionary. If
1629the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data
1630descriptor; if it defines neither, it is a non-data descriptor. Normally, data
1631descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data
1632descriptors have just the :meth:`__get__` method. Data descriptors with
1633:meth:`__set__` and :meth:`__get__` defined always override a redefinition in an
Georg Brandl8ec7f652007-08-15 14:28:01 +00001634instance dictionary. In contrast, non-data descriptors can be overridden by
Benjamin Peterson9179dab2010-01-18 23:07:56 +00001635instances.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001636
1637Python methods (including :func:`staticmethod` and :func:`classmethod`) are
1638implemented as non-data descriptors. Accordingly, instances can redefine and
1639override methods. This allows individual instances to acquire behaviors that
1640differ from other instances of the same class.
1641
1642The :func:`property` function is implemented as a data descriptor. Accordingly,
1643instances cannot override the behavior of a property.
1644
1645
1646.. _slots:
1647
1648__slots__
1649^^^^^^^^^
1650
1651By default, instances of both old and new-style classes have a dictionary for
1652attribute storage. This wastes space for objects having very few instance
1653variables. The space consumption can become acute when creating large numbers
1654of instances.
1655
1656The default can be overridden by defining *__slots__* in a new-style class
1657definition. The *__slots__* declaration takes a sequence of instance variables
1658and reserves just enough space in each instance to hold a value for each
1659variable. Space is saved because *__dict__* is not created for each instance.
1660
1661
1662.. data:: __slots__
1663
1664 This class variable can be assigned a string, iterable, or sequence of strings
1665 with variable names used by instances. If defined in a new-style class,
1666 *__slots__* reserves space for the declared variables and prevents the automatic
1667 creation of *__dict__* and *__weakref__* for each instance.
1668
1669 .. versionadded:: 2.2
1670
1671Notes on using *__slots__*
1672
Georg Brandl3de1e692008-07-19 13:09:42 +00001673* When inheriting from a class without *__slots__*, the *__dict__* attribute of
1674 that class will always be accessible, so a *__slots__* definition in the
1675 subclass is meaningless.
1676
Georg Brandl8ec7f652007-08-15 14:28:01 +00001677* Without a *__dict__* variable, instances cannot be assigned new variables not
1678 listed in the *__slots__* definition. Attempts to assign to an unlisted
1679 variable name raises :exc:`AttributeError`. If dynamic assignment of new
1680 variables is desired, then add ``'__dict__'`` to the sequence of strings in the
1681 *__slots__* declaration.
1682
1683 .. versionchanged:: 2.3
1684 Previously, adding ``'__dict__'`` to the *__slots__* declaration would not
1685 enable the assignment of new attributes not specifically listed in the sequence
1686 of instance variable names.
1687
1688* Without a *__weakref__* variable for each instance, classes defining
1689 *__slots__* do not support weak references to its instances. If weak reference
1690 support is needed, then add ``'__weakref__'`` to the sequence of strings in the
1691 *__slots__* declaration.
1692
1693 .. versionchanged:: 2.3
1694 Previously, adding ``'__weakref__'`` to the *__slots__* declaration would not
1695 enable support for weak references.
1696
1697* *__slots__* are implemented at the class level by creating descriptors
1698 (:ref:`descriptors`) for each variable name. As a result, class attributes
1699 cannot be used to set default values for instance variables defined by
1700 *__slots__*; otherwise, the class attribute would overwrite the descriptor
1701 assignment.
1702
Georg Brandl030d6582009-10-22 15:27:24 +00001703* The action of a *__slots__* declaration is limited to the class where it is
1704 defined. As a result, subclasses will have a *__dict__* unless they also define
1705 *__slots__* (which must only contain names of any *additional* slots).
1706
Georg Brandl8ec7f652007-08-15 14:28:01 +00001707* If a class defines a slot also defined in a base class, the instance variable
1708 defined by the base class slot is inaccessible (except by retrieving its
1709 descriptor directly from the base class). This renders the meaning of the
1710 program undefined. In the future, a check may be added to prevent this.
1711
Benjamin Petersonc756dcd2008-10-23 21:43:48 +00001712* Nonempty *__slots__* does not work for classes derived from "variable-length"
1713 built-in types such as :class:`long`, :class:`str` and :class:`tuple`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001714
1715* Any non-string iterable may be assigned to *__slots__*. Mappings may also be
1716 used; however, in the future, special meaning may be assigned to the values
1717 corresponding to each key.
1718
1719* *__class__* assignment works only if both classes have the same *__slots__*.
1720
1721 .. versionchanged:: 2.6
1722 Previously, *__class__* assignment raised an error if either new or old class
1723 had *__slots__*.
1724
1725
1726.. _metaclasses:
1727
1728Customizing class creation
1729--------------------------
1730
1731By default, new-style classes are constructed using :func:`type`. A class
1732definition is read into a separate namespace and the value of class name is
1733bound to the result of ``type(name, bases, dict)``.
1734
1735When the class definition is read, if *__metaclass__* is defined then the
Georg Brandl3ccb49a2008-01-07 19:17:10 +00001736callable assigned to it will be called instead of :func:`type`. This allows
Georg Brandl8ec7f652007-08-15 14:28:01 +00001737classes or functions to be written which monitor or alter the class creation
1738process:
1739
1740* Modifying the class dictionary prior to the class being created.
1741
1742* Returning an instance of another class -- essentially performing the role of a
1743 factory function.
1744
Georg Brandl3ccb49a2008-01-07 19:17:10 +00001745These steps will have to be performed in the metaclass's :meth:`__new__` method
1746-- :meth:`type.__new__` can then be called from this method to create a class
1747with different properties. This example adds a new element to the class
1748dictionary before creating the class::
1749
1750 class metacls(type):
1751 def __new__(mcs, name, bases, dict):
1752 dict['foo'] = 'metacls was here'
1753 return type.__new__(mcs, name, bases, dict)
1754
1755You can of course also override other class methods (or add new methods); for
1756example defining a custom :meth:`__call__` method in the metaclass allows custom
1757behavior when the class is called, e.g. not always creating a new instance.
1758
Georg Brandl8ec7f652007-08-15 14:28:01 +00001759
1760.. data:: __metaclass__
1761
1762 This variable can be any callable accepting arguments for ``name``, ``bases``,
1763 and ``dict``. Upon class creation, the callable is used instead of the built-in
1764 :func:`type`.
1765
1766 .. versionadded:: 2.2
1767
1768The appropriate metaclass is determined by the following precedence rules:
1769
1770* If ``dict['__metaclass__']`` exists, it is used.
1771
1772* Otherwise, if there is at least one base class, its metaclass is used (this
1773 looks for a *__class__* attribute first and if not found, uses its type).
1774
1775* Otherwise, if a global variable named __metaclass__ exists, it is used.
1776
1777* Otherwise, the old-style, classic metaclass (types.ClassType) is used.
1778
1779The potential uses for metaclasses are boundless. Some ideas that have been
1780explored including logging, interface checking, automatic delegation, automatic
1781property creation, proxies, frameworks, and automatic resource
1782locking/synchronization.
1783
1784
Georg Brandl710a5db2010-04-14 21:34:44 +00001785Customizing instance and subclass checks
1786----------------------------------------
1787
1788.. versionadded:: 2.6
1789
1790The following methods are used to override the default behavior of the
1791:func:`isinstance` and :func:`issubclass` built-in functions.
1792
1793In particular, the metaclass :class:`abc.ABCMeta` implements these methods in
1794order to allow the addition of Abstract Base Classes (ABCs) as "virtual base
Andrew M. Kuchlingb3437c92010-04-30 13:46:55 +00001795classes" to any class or type (including built-in types), including other
Georg Brandl710a5db2010-04-14 21:34:44 +00001796ABCs.
1797
1798.. method:: class.__instancecheck__(self, instance)
1799
1800 Return true if *instance* should be considered a (direct or indirect)
1801 instance of *class*. If defined, called to implement ``isinstance(instance,
1802 class)``.
1803
1804
1805.. method:: class.__subclasscheck__(self, subclass)
1806
1807 Return true if *subclass* should be considered a (direct or indirect)
1808 subclass of *class*. If defined, called to implement ``issubclass(subclass,
1809 class)``.
1810
1811
1812Note that these methods are looked up on the type (metaclass) of a class. They
1813cannot be defined as class methods in the actual class. This is consistent with
Andrew M. Kuchlingb3437c92010-04-30 13:46:55 +00001814the lookup of special methods that are called on instances, only in this
Georg Brandl9f5fd602010-04-14 21:46:45 +00001815case the instance is itself a class.
Georg Brandl710a5db2010-04-14 21:34:44 +00001816
1817.. seealso::
1818
1819 :pep:`3119` - Introducing Abstract Base Classes
1820 Includes the specification for customizing :func:`isinstance` and
Serhiy Storchakaad16b722013-10-09 14:02:14 +03001821 :func:`issubclass` behavior through :meth:`~class.__instancecheck__` and
1822 :meth:`~class.__subclasscheck__`, with motivation for this functionality
1823 in the context of adding Abstract Base Classes (see the :mod:`abc`
1824 module) to the language.
Georg Brandl710a5db2010-04-14 21:34:44 +00001825
1826
Georg Brandl8ec7f652007-08-15 14:28:01 +00001827.. _callable-types:
1828
1829Emulating callable objects
1830--------------------------
1831
1832
1833.. method:: object.__call__(self[, args...])
1834
1835 .. index:: pair: call; instance
1836
1837 Called when the instance is "called" as a function; if this method is defined,
1838 ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``.
1839
1840
1841.. _sequence-types:
1842
1843Emulating container types
1844-------------------------
1845
1846The following methods can be defined to implement container objects. Containers
1847usually are sequences (such as lists or tuples) or mappings (like dictionaries),
1848but can represent other containers as well. The first set of methods is used
1849either to emulate a sequence or to emulate a mapping; the difference is that for
1850a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
1851N`` where *N* is the length of the sequence, or slice objects, which define a
1852range of items. (For backwards compatibility, the method :meth:`__getslice__`
1853(see below) can also be defined to handle simple, but not extended slices.) It
1854is also recommended that mappings provide the methods :meth:`keys`,
1855:meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, :meth:`clear`,
1856:meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, :meth:`iteritems`,
Serhiy Storchakaad16b722013-10-09 14:02:14 +03001857:meth:`pop`, :meth:`popitem`, :meth:`!copy`, and :meth:`update` behaving similar
Georg Brandl8ec7f652007-08-15 14:28:01 +00001858to those for Python's standard dictionary objects. The :mod:`UserDict` module
1859provides a :class:`DictMixin` class to help create those methods from a base set
1860of :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and
1861:meth:`keys`. Mutable sequences should provide methods :meth:`append`,
1862:meth:`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`,
1863:meth:`remove`, :meth:`reverse` and :meth:`sort`, like Python standard list
1864objects. Finally, sequence types should implement addition (meaning
1865concatenation) and multiplication (meaning repetition) by defining the methods
1866:meth:`__add__`, :meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`,
1867:meth:`__rmul__` and :meth:`__imul__` described below; they should not define
1868:meth:`__coerce__` or other numerical operators. It is recommended that both
1869mappings and sequences implement the :meth:`__contains__` method to allow
1870efficient use of the ``in`` operator; for mappings, ``in`` should be equivalent
1871of :meth:`has_key`; for sequences, it should search through the values. It is
1872further recommended that both mappings and sequences implement the
1873:meth:`__iter__` method to allow efficient iteration through the container; for
1874mappings, :meth:`__iter__` should be the same as :meth:`iterkeys`; for
1875sequences, it should iterate through the values.
1876
1877
1878.. method:: object.__len__(self)
1879
1880 .. index::
1881 builtin: len
1882 single: __nonzero__() (object method)
1883
1884 Called to implement the built-in function :func:`len`. Should return the length
1885 of the object, an integer ``>=`` 0. Also, an object that doesn't define a
1886 :meth:`__nonzero__` method and whose :meth:`__len__` method returns zero is
1887 considered to be false in a Boolean context.
1888
1889
1890.. method:: object.__getitem__(self, key)
1891
1892 .. index:: object: slice
1893
1894 Called to implement evaluation of ``self[key]``. For sequence types, the
1895 accepted keys should be integers and slice objects. Note that the special
1896 interpretation of negative indexes (if the class wishes to emulate a sequence
1897 type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate
1898 type, :exc:`TypeError` may be raised; if of a value outside the set of indexes
1899 for the sequence (after any special interpretation of negative values),
1900 :exc:`IndexError` should be raised. For mapping types, if *key* is missing (not
1901 in the container), :exc:`KeyError` should be raised.
1902
1903 .. note::
1904
1905 :keyword:`for` loops expect that an :exc:`IndexError` will be raised for illegal
1906 indexes to allow proper detection of the end of the sequence.
1907
1908
1909.. method:: object.__setitem__(self, key, value)
1910
1911 Called to implement assignment to ``self[key]``. Same note as for
1912 :meth:`__getitem__`. This should only be implemented for mappings if the
1913 objects support changes to the values for keys, or if new keys can be added, or
1914 for sequences if elements can be replaced. The same exceptions should be raised
1915 for improper *key* values as for the :meth:`__getitem__` method.
1916
1917
1918.. method:: object.__delitem__(self, key)
1919
1920 Called to implement deletion of ``self[key]``. Same note as for
1921 :meth:`__getitem__`. This should only be implemented for mappings if the
1922 objects support removal of keys, or for sequences if elements can be removed
1923 from the sequence. The same exceptions should be raised for improper *key*
1924 values as for the :meth:`__getitem__` method.
1925
1926
1927.. method:: object.__iter__(self)
1928
1929 This method is called when an iterator is required for a container. This method
1930 should return a new iterator object that can iterate over all the objects in the
1931 container. For mappings, it should iterate over the keys of the container, and
1932 should also be made available as the method :meth:`iterkeys`.
1933
1934 Iterator objects also need to implement this method; they are required to return
1935 themselves. For more information on iterator objects, see :ref:`typeiter`.
1936
Georg Brandl81de0d22008-01-06 16:17:56 +00001937
1938.. method:: object.__reversed__(self)
1939
Georg Brandld7d4fd72009-07-26 14:37:28 +00001940 Called (if present) by the :func:`reversed` built-in to implement
Georg Brandl81de0d22008-01-06 16:17:56 +00001941 reverse iteration. It should return a new iterator object that iterates
1942 over all the objects in the container in reverse order.
1943
Georg Brandl8dc3b442009-05-16 11:13:21 +00001944 If the :meth:`__reversed__` method is not provided, the :func:`reversed`
Georg Brandld7d4fd72009-07-26 14:37:28 +00001945 built-in will fall back to using the sequence protocol (:meth:`__len__` and
Georg Brandl8dc3b442009-05-16 11:13:21 +00001946 :meth:`__getitem__`). Objects that support the sequence protocol should
1947 only provide :meth:`__reversed__` if they can provide an implementation
1948 that is more efficient than the one provided by :func:`reversed`.
Georg Brandl81de0d22008-01-06 16:17:56 +00001949
1950 .. versionadded:: 2.6
1951
1952
Georg Brandl8ec7f652007-08-15 14:28:01 +00001953The membership test operators (:keyword:`in` and :keyword:`not in`) are normally
1954implemented as an iteration through a sequence. However, container objects can
1955supply the following special method with a more efficient implementation, which
1956also does not require the object be a sequence.
1957
Georg Brandl8ec7f652007-08-15 14:28:01 +00001958.. method:: object.__contains__(self, item)
1959
Georg Brandl2eee1d42009-10-22 15:00:06 +00001960 Called to implement membership test operators. Should return true if *item*
1961 is in *self*, false otherwise. For mapping objects, this should consider the
1962 keys of the mapping rather than the values or the key-item pairs.
1963
1964 For objects that don't define :meth:`__contains__`, the membership test first
1965 tries iteration via :meth:`__iter__`, then the old sequence iteration
1966 protocol via :meth:`__getitem__`, see :ref:`this section in the language
1967 reference <membership-test-details>`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001968
1969
1970.. _sequence-methods:
1971
1972Additional methods for emulation of sequence types
1973--------------------------------------------------
1974
1975The following optional methods can be defined to further emulate sequence
1976objects. Immutable sequences methods should at most only define
1977:meth:`__getslice__`; mutable sequences might define all three methods.
1978
1979
1980.. method:: object.__getslice__(self, i, j)
1981
1982 .. deprecated:: 2.0
1983 Support slice objects as parameters to the :meth:`__getitem__` method.
Georg Brandl8d9e8452007-08-23 20:35:00 +00001984 (However, built-in types in CPython currently still implement
1985 :meth:`__getslice__`. Therefore, you have to override it in derived
1986 classes when implementing slicing.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001987
1988 Called to implement evaluation of ``self[i:j]``. The returned object should be
1989 of the same type as *self*. Note that missing *i* or *j* in the slice
1990 expression are replaced by zero or ``sys.maxint``, respectively. If negative
1991 indexes are used in the slice, the length of the sequence is added to that
1992 index. If the instance does not implement the :meth:`__len__` method, an
1993 :exc:`AttributeError` is raised. No guarantee is made that indexes adjusted this
1994 way are not still negative. Indexes which are greater than the length of the
1995 sequence are not modified. If no :meth:`__getslice__` is found, a slice object
1996 is created instead, and passed to :meth:`__getitem__` instead.
1997
1998
1999.. method:: object.__setslice__(self, i, j, sequence)
2000
2001 Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as
2002 for :meth:`__getslice__`.
2003
2004 This method is deprecated. If no :meth:`__setslice__` is found, or for extended
2005 slicing of the form ``self[i:j:k]``, a slice object is created, and passed to
2006 :meth:`__setitem__`, instead of :meth:`__setslice__` being called.
2007
2008
2009.. method:: object.__delslice__(self, i, j)
2010
2011 Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for
2012 :meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
2013 found, or for extended slicing of the form ``self[i:j:k]``, a slice object is
2014 created, and passed to :meth:`__delitem__`, instead of :meth:`__delslice__`
2015 being called.
2016
2017Notice that these methods are only invoked when a single slice with a single
2018colon is used, and the slice method is available. For slice operations
2019involving extended slice notation, or in absence of the slice methods,
2020:meth:`__getitem__`, :meth:`__setitem__` or :meth:`__delitem__` is called with a
2021slice object as argument.
2022
2023The following example demonstrate how to make your program or module compatible
2024with earlier versions of Python (assuming that methods :meth:`__getitem__`,
2025:meth:`__setitem__` and :meth:`__delitem__` support slice objects as
2026arguments)::
2027
2028 class MyClass:
2029 ...
2030 def __getitem__(self, index):
2031 ...
2032 def __setitem__(self, index, value):
2033 ...
2034 def __delitem__(self, index):
2035 ...
2036
2037 if sys.version_info < (2, 0):
2038 # They won't be defined if version is at least 2.0 final
2039
2040 def __getslice__(self, i, j):
2041 return self[max(0, i):max(0, j):]
2042 def __setslice__(self, i, j, seq):
2043 self[max(0, i):max(0, j):] = seq
2044 def __delslice__(self, i, j):
2045 del self[max(0, i):max(0, j):]
2046 ...
2047
2048Note the calls to :func:`max`; these are necessary because of the handling of
2049negative indices before the :meth:`__\*slice__` methods are called. When
2050negative indexes are used, the :meth:`__\*item__` methods receive them as
2051provided, but the :meth:`__\*slice__` methods get a "cooked" form of the index
2052values. For each negative index value, the length of the sequence is added to
2053the index before calling the method (which may still result in a negative
2054index); this is the customary handling of negative indexes by the built-in
2055sequence types, and the :meth:`__\*item__` methods are expected to do this as
2056well. However, since they should already be doing that, negative indexes cannot
2057be passed in; they must be constrained to the bounds of the sequence before
2058being passed to the :meth:`__\*item__` methods. Calling ``max(0, i)``
2059conveniently returns the proper value.
2060
2061
2062.. _numeric-types:
2063
2064Emulating numeric types
2065-----------------------
2066
2067The following methods can be defined to emulate numeric objects. Methods
2068corresponding to operations that are not supported by the particular kind of
2069number implemented (e.g., bitwise operations for non-integral numbers) should be
2070left undefined.
2071
2072
2073.. method:: object.__add__(self, other)
2074 object.__sub__(self, other)
2075 object.__mul__(self, other)
2076 object.__floordiv__(self, other)
2077 object.__mod__(self, other)
2078 object.__divmod__(self, other)
2079 object.__pow__(self, other[, modulo])
2080 object.__lshift__(self, other)
2081 object.__rshift__(self, other)
2082 object.__and__(self, other)
2083 object.__xor__(self, other)
2084 object.__or__(self, other)
2085
2086 .. index::
2087 builtin: divmod
2088 builtin: pow
2089 builtin: pow
2090
2091 These methods are called to implement the binary arithmetic operations (``+``,
2092 ``-``, ``*``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``,
2093 ``>>``, ``&``, ``^``, ``|``). For instance, to evaluate the expression
Brett Cannon93298462008-08-14 05:55:18 +00002094 ``x + y``, where *x* is an instance of a class that has an :meth:`__add__`
Georg Brandl8ec7f652007-08-15 14:28:01 +00002095 method, ``x.__add__(y)`` is called. The :meth:`__divmod__` method should be the
2096 equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be
2097 related to :meth:`__truediv__` (described below). Note that :meth:`__pow__`
2098 should be defined to accept an optional third argument if the ternary version of
2099 the built-in :func:`pow` function is to be supported.
2100
2101 If one of those methods does not support the operation with the supplied
2102 arguments, it should return ``NotImplemented``.
2103
2104
2105.. method:: object.__div__(self, other)
2106 object.__truediv__(self, other)
2107
2108 The division operator (``/``) is implemented by these methods. The
2109 :meth:`__truediv__` method is used when ``__future__.division`` is in effect,
2110 otherwise :meth:`__div__` is used. If only one of these two methods is defined,
2111 the object will not support division in the alternate context; :exc:`TypeError`
2112 will be raised instead.
2113
2114
2115.. method:: object.__radd__(self, other)
2116 object.__rsub__(self, other)
2117 object.__rmul__(self, other)
2118 object.__rdiv__(self, other)
2119 object.__rtruediv__(self, other)
2120 object.__rfloordiv__(self, other)
2121 object.__rmod__(self, other)
2122 object.__rdivmod__(self, other)
2123 object.__rpow__(self, other)
2124 object.__rlshift__(self, other)
2125 object.__rrshift__(self, other)
2126 object.__rand__(self, other)
2127 object.__rxor__(self, other)
2128 object.__ror__(self, other)
2129
2130 .. index::
2131 builtin: divmod
2132 builtin: pow
2133
2134 These methods are called to implement the binary arithmetic operations (``+``,
2135 ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``,
2136 ``&``, ``^``, ``|``) with reflected (swapped) operands. These functions are
2137 only called if the left operand does not support the corresponding operation and
2138 the operands are of different types. [#]_ For instance, to evaluate the
Brett Cannon93298462008-08-14 05:55:18 +00002139 expression ``x - y``, where *y* is an instance of a class that has an
Georg Brandl8ec7f652007-08-15 14:28:01 +00002140 :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns
2141 *NotImplemented*.
2142
2143 .. index:: builtin: pow
2144
2145 Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
2146 coercion rules would become too complicated).
2147
2148 .. note::
2149
2150 If the right operand's type is a subclass of the left operand's type and that
2151 subclass provides the reflected method for the operation, this method will be
2152 called before the left operand's non-reflected method. This behavior allows
2153 subclasses to override their ancestors' operations.
2154
2155
2156.. method:: object.__iadd__(self, other)
2157 object.__isub__(self, other)
2158 object.__imul__(self, other)
2159 object.__idiv__(self, other)
2160 object.__itruediv__(self, other)
2161 object.__ifloordiv__(self, other)
2162 object.__imod__(self, other)
2163 object.__ipow__(self, other[, modulo])
2164 object.__ilshift__(self, other)
2165 object.__irshift__(self, other)
2166 object.__iand__(self, other)
2167 object.__ixor__(self, other)
2168 object.__ior__(self, other)
2169
Georg Brandlfe11f4d2009-01-18 18:25:30 +00002170 These methods are called to implement the augmented arithmetic assignments
Georg Brandl8ec7f652007-08-15 14:28:01 +00002171 (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
2172 ``&=``, ``^=``, ``|=``). These methods should attempt to do the operation
2173 in-place (modifying *self*) and return the result (which could be, but does
2174 not have to be, *self*). If a specific method is not defined, the augmented
Georg Brandlfe11f4d2009-01-18 18:25:30 +00002175 assignment falls back to the normal methods. For instance, to execute the
2176 statement ``x += y``, where *x* is an instance of a class that has an
Georg Brandl8ec7f652007-08-15 14:28:01 +00002177 :meth:`__iadd__` method, ``x.__iadd__(y)`` is called. If *x* is an instance
2178 of a class that does not define a :meth:`__iadd__` method, ``x.__add__(y)``
Brett Cannon93298462008-08-14 05:55:18 +00002179 and ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002180
2181
2182.. method:: object.__neg__(self)
2183 object.__pos__(self)
2184 object.__abs__(self)
2185 object.__invert__(self)
2186
2187 .. index:: builtin: abs
2188
2189 Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
2190 and ``~``).
2191
2192
2193.. method:: object.__complex__(self)
2194 object.__int__(self)
2195 object.__long__(self)
2196 object.__float__(self)
2197
2198 .. index::
2199 builtin: complex
2200 builtin: int
2201 builtin: long
2202 builtin: float
2203
2204 Called to implement the built-in functions :func:`complex`, :func:`int`,
2205 :func:`long`, and :func:`float`. Should return a value of the appropriate type.
2206
2207
2208.. method:: object.__oct__(self)
2209 object.__hex__(self)
2210
2211 .. index::
2212 builtin: oct
2213 builtin: hex
2214
2215 Called to implement the built-in functions :func:`oct` and :func:`hex`. Should
2216 return a string value.
2217
2218
2219.. method:: object.__index__(self)
2220
2221 Called to implement :func:`operator.index`. Also called whenever Python needs
2222 an integer object (such as in slicing). Must return an integer (int or long).
2223
2224 .. versionadded:: 2.5
2225
2226
2227.. method:: object.__coerce__(self, other)
2228
2229 Called to implement "mixed-mode" numeric arithmetic. Should either return a
2230 2-tuple containing *self* and *other* converted to a common numeric type, or
2231 ``None`` if conversion is impossible. When the common type would be the type of
2232 ``other``, it is sufficient to return ``None``, since the interpreter will also
2233 ask the other object to attempt a coercion (but sometimes, if the implementation
2234 of the other type cannot be changed, it is useful to do the conversion to the
2235 other type here). A return value of ``NotImplemented`` is equivalent to
2236 returning ``None``.
2237
2238
2239.. _coercion-rules:
2240
2241Coercion rules
2242--------------
2243
2244This section used to document the rules for coercion. As the language has
2245evolved, the coercion rules have become hard to document precisely; documenting
2246what one version of one particular implementation does is undesirable. Instead,
Ezio Melotti510ff542012-05-03 19:21:40 +03002247here are some informal guidelines regarding coercion. In Python 3, coercion
Georg Brandl8ec7f652007-08-15 14:28:01 +00002248will not be supported.
2249
2250*
2251
2252 If the left operand of a % operator is a string or Unicode object, no coercion
2253 takes place and the string formatting operation is invoked instead.
2254
2255*
2256
2257 It is no longer recommended to define a coercion operation. Mixed-mode
2258 operations on types that don't define coercion pass the original arguments to
2259 the operation.
2260
2261*
2262
2263 New-style classes (those derived from :class:`object`) never invoke the
2264 :meth:`__coerce__` method in response to a binary operator; the only time
2265 :meth:`__coerce__` is invoked is when the built-in function :func:`coerce` is
2266 called.
2267
2268*
2269
2270 For most intents and purposes, an operator that returns ``NotImplemented`` is
2271 treated the same as one that is not implemented at all.
2272
2273*
2274
2275 Below, :meth:`__op__` and :meth:`__rop__` are used to signify the generic method
2276 names corresponding to an operator; :meth:`__iop__` is used for the
2277 corresponding in-place operator. For example, for the operator '``+``',
2278 :meth:`__add__` and :meth:`__radd__` are used for the left and right variant of
2279 the binary operator, and :meth:`__iadd__` for the in-place variant.
2280
2281*
2282
2283 For objects *x* and *y*, first ``x.__op__(y)`` is tried. If this is not
2284 implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is tried. If this
2285 is also not implemented or returns ``NotImplemented``, a :exc:`TypeError`
2286 exception is raised. But see the following exception:
2287
2288*
2289
2290 Exception to the previous item: if the left operand is an instance of a built-in
2291 type or a new-style class, and the right operand is an instance of a proper
2292 subclass of that type or class and overrides the base's :meth:`__rop__` method,
2293 the right operand's :meth:`__rop__` method is tried *before* the left operand's
2294 :meth:`__op__` method.
2295
2296 This is done so that a subclass can completely override binary operators.
2297 Otherwise, the left operand's :meth:`__op__` method would always accept the
2298 right operand: when an instance of a given class is expected, an instance of a
2299 subclass of that class is always acceptable.
2300
2301*
2302
2303 When either operand type defines a coercion, this coercion is called before that
2304 type's :meth:`__op__` or :meth:`__rop__` method is called, but no sooner. If
2305 the coercion returns an object of a different type for the operand whose
2306 coercion is invoked, part of the process is redone using the new object.
2307
2308*
2309
2310 When an in-place operator (like '``+=``') is used, if the left operand
2311 implements :meth:`__iop__`, it is invoked without any coercion. When the
2312 operation falls back to :meth:`__op__` and/or :meth:`__rop__`, the normal
2313 coercion rules apply.
2314
2315*
2316
Brett Cannon93298462008-08-14 05:55:18 +00002317 In ``x + y``, if *x* is a sequence that implements sequence concatenation,
Georg Brandl8ec7f652007-08-15 14:28:01 +00002318 sequence concatenation is invoked.
2319
2320*
2321
Eli Bendersky761473f2011-06-10 10:36:34 +03002322 In ``x * y``, if one operand is a sequence that implements sequence
Georg Brandl8ec7f652007-08-15 14:28:01 +00002323 repetition, and the other is an integer (:class:`int` or :class:`long`),
2324 sequence repetition is invoked.
2325
2326*
2327
2328 Rich comparisons (implemented by methods :meth:`__eq__` and so on) never use
2329 coercion. Three-way comparison (implemented by :meth:`__cmp__`) does use
2330 coercion under the same conditions as other binary operations use it.
2331
2332*
2333
2334 In the current implementation, the built-in numeric types :class:`int`,
Mark Dickinson82b34c52010-02-21 12:57:35 +00002335 :class:`long`, :class:`float`, and :class:`complex` do not use coercion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002336 All these types implement a :meth:`__coerce__` method, for use by the built-in
2337 :func:`coerce` function.
2338
Mark Dickinson82b34c52010-02-21 12:57:35 +00002339 .. versionchanged:: 2.7
2340
2341 The complex type no longer makes implicit calls to the :meth:`__coerce__`
2342 method for mixed-type binary arithmetic operations.
2343
Georg Brandl8ec7f652007-08-15 14:28:01 +00002344
2345.. _context-managers:
2346
2347With Statement Context Managers
2348-------------------------------
2349
2350.. versionadded:: 2.5
2351
2352A :dfn:`context manager` is an object that defines the runtime context to be
2353established when executing a :keyword:`with` statement. The context manager
2354handles the entry into, and the exit from, the desired runtime context for the
2355execution of the block of code. Context managers are normally invoked using the
2356:keyword:`with` statement (described in section :ref:`with`), but can also be
2357used by directly invoking their methods.
2358
2359.. index::
2360 statement: with
2361 single: context manager
2362
2363Typical uses of context managers include saving and restoring various kinds of
2364global state, locking and unlocking resources, closing opened files, etc.
2365
2366For more information on context managers, see :ref:`typecontextmanager`.
2367
2368
2369.. method:: object.__enter__(self)
2370
2371 Enter the runtime context related to this object. The :keyword:`with` statement
2372 will bind this method's return value to the target(s) specified in the
2373 :keyword:`as` clause of the statement, if any.
2374
2375
2376.. method:: object.__exit__(self, exc_type, exc_value, traceback)
2377
2378 Exit the runtime context related to this object. The parameters describe the
2379 exception that caused the context to be exited. If the context was exited
2380 without an exception, all three arguments will be :const:`None`.
2381
2382 If an exception is supplied, and the method wishes to suppress the exception
2383 (i.e., prevent it from being propagated), it should return a true value.
2384 Otherwise, the exception will be processed normally upon exit from this method.
2385
2386 Note that :meth:`__exit__` methods should not reraise the passed-in exception;
2387 this is the caller's responsibility.
2388
2389
2390.. seealso::
2391
2392 :pep:`0343` - The "with" statement
2393 The specification, background, and examples for the Python :keyword:`with`
2394 statement.
2395
Nick Coghlana5107482008-08-04 12:40:59 +00002396
2397.. _old-style-special-lookup:
2398
2399Special method lookup for old-style classes
2400-------------------------------------------
2401
2402For old-style classes, special methods are always looked up in exactly the
2403same way as any other method or attribute. This is the case regardless of
2404whether the method is being looked up explicitly as in ``x.__getitem__(i)``
2405or implicitly as in ``x[i]``.
2406
2407This behaviour means that special methods may exhibit different behaviour
2408for different instances of a single old-style class if the appropriate
2409special attributes are set differently::
2410
2411 >>> class C:
2412 ... pass
2413 ...
2414 >>> c1 = C()
2415 >>> c2 = C()
2416 >>> c1.__len__ = lambda: 5
2417 >>> c2.__len__ = lambda: 9
2418 >>> len(c1)
2419 5
2420 >>> len(c2)
2421 9
2422
2423
2424.. _new-style-special-lookup:
2425
2426Special method lookup for new-style classes
2427-------------------------------------------
2428
2429For new-style classes, implicit invocations of special methods are only guaranteed
2430to work correctly if defined on an object's type, not in the object's instance
2431dictionary. That behaviour is the reason why the following code raises an
2432exception (unlike the equivalent example with old-style classes)::
2433
2434 >>> class C(object):
2435 ... pass
2436 ...
2437 >>> c = C()
2438 >>> c.__len__ = lambda: 5
2439 >>> len(c)
2440 Traceback (most recent call last):
2441 File "<stdin>", line 1, in <module>
2442 TypeError: object of type 'C' has no len()
2443
2444The rationale behind this behaviour lies with a number of special methods such
2445as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects,
2446including type objects. If the implicit lookup of these methods used the
2447conventional lookup process, they would fail when invoked on the type object
2448itself::
2449
2450 >>> 1 .__hash__() == hash(1)
2451 True
2452 >>> int.__hash__() == hash(int)
2453 Traceback (most recent call last):
2454 File "<stdin>", line 1, in <module>
2455 TypeError: descriptor '__hash__' of 'int' object needs an argument
2456
2457Incorrectly attempting to invoke an unbound method of a class in this way is
2458sometimes referred to as 'metaclass confusion', and is avoided by bypassing
2459the instance when looking up special methods::
2460
2461 >>> type(1).__hash__(1) == hash(1)
2462 True
2463 >>> type(int).__hash__(int) == hash(int)
2464 True
2465
2466In addition to bypassing any instance attributes in the interest of
Georg Brandl9a053732008-12-05 15:29:39 +00002467correctness, implicit special method lookup generally also bypasses the
Nick Coghlana5107482008-08-04 12:40:59 +00002468:meth:`__getattribute__` method even of the object's metaclass::
2469
2470 >>> class Meta(type):
2471 ... def __getattribute__(*args):
2472 ... print "Metaclass getattribute invoked"
2473 ... return type.__getattribute__(*args)
2474 ...
2475 >>> class C(object):
2476 ... __metaclass__ = Meta
2477 ... def __len__(self):
2478 ... return 10
2479 ... def __getattribute__(*args):
2480 ... print "Class getattribute invoked"
2481 ... return object.__getattribute__(*args)
2482 ...
2483 >>> c = C()
2484 >>> c.__len__() # Explicit lookup via instance
2485 Class getattribute invoked
2486 10
2487 >>> type(c).__len__(c) # Explicit lookup via type
2488 Metaclass getattribute invoked
2489 10
2490 >>> len(c) # Implicit lookup
2491 10
2492
2493Bypassing the :meth:`__getattribute__` machinery in this fashion
2494provides significant scope for speed optimisations within the
2495interpreter, at the cost of some flexibility in the handling of
2496special methods (the special method *must* be set on the class
2497object itself in order to be consistently invoked by the interpreter).
2498
2499
Georg Brandl8ec7f652007-08-15 14:28:01 +00002500.. rubric:: Footnotes
2501
Nick Coghlana5107482008-08-04 12:40:59 +00002502.. [#] It *is* possible in some cases to change an object's type, under certain
2503 controlled conditions. It generally isn't a good idea though, since it can
2504 lead to some very strange behaviour if it is handled incorrectly.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002505
Georg Brandl8ec7f652007-08-15 14:28:01 +00002506.. [#] For operands of the same type, it is assumed that if the non-reflected method
2507 (such as :meth:`__add__`) fails the operation is not supported, which is why the
2508 reflected method is not called.
2509