blob: 85953ad1e25c7f1043951940eb25946d564161b4 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl85eb8c12007-08-31 16:33:38 +000032.. XXX it *is* now possible in some cases to change an object's
33 type, under certain controlled conditions
34
Georg Brandl116aa622007-08-15 14:28:22 +000035Every object has an identity, a type and a value. An object's *identity* never
36changes once it has been created; you may think of it as the object's address in
37memory. The ':keyword:`is`' operator compares the identity of two objects; the
38:func:`id` function returns an integer representing its identity (currently
Nick Coghlan3a5d7e32008-08-31 12:40:14 +000039implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +000040An object's type determines the operations that the object supports (e.g., "does
41it have a length?") and also defines the possible values for objects of that
42type. The :func:`type` function returns an object's type (which is an object
43itself). The *value* of some objects can change. Objects whose value can
44change are said to be *mutable*; objects whose value is unchangeable once they
45are created are called *immutable*. (The value of an immutable container object
46that contains a reference to a mutable object can change when the latter's value
47is changed; however the container is still considered immutable, because the
48collection of objects it contains cannot be changed. So, immutability is not
49strictly the same as having an unchangeable value, it is more subtle.) An
50object's mutability is determined by its type; for instance, numbers, strings
51and tuples are immutable, while dictionaries and lists are mutable.
52
53.. index::
54 single: garbage collection
55 single: reference counting
56 single: unreachable object
57
58Objects are never explicitly destroyed; however, when they become unreachable
59they may be garbage-collected. An implementation is allowed to postpone garbage
60collection or omit it altogether --- it is a matter of implementation quality
61how garbage collection is implemented, as long as no objects are collected that
Georg Brandl495f7b52009-10-27 15:28:25 +000062are still reachable.
63
64.. impl-detail::
65
66 CPython currently uses a reference-counting scheme with (optional) delayed
67 detection of cyclically linked garbage, which collects most objects as soon
68 as they become unreachable, but is not guaranteed to collect garbage
69 containing circular references. See the documentation of the :mod:`gc`
70 module for information on controlling the collection of cyclic garbage.
71 Other implementations act differently and CPython may change.
Gregory P. Smithc5425472011-03-10 11:28:50 -080072 Do not depend on immediate finalization of objects when they become
73 unreachable (ex: always close files).
Georg Brandl116aa622007-08-15 14:28:22 +000074
75Note that the use of the implementation's tracing or debugging facilities may
76keep objects alive that would normally be collectable. Also note that catching
77an exception with a ':keyword:`try`...\ :keyword:`except`' statement may keep
78objects alive.
79
80Some objects contain references to "external" resources such as open files or
81windows. It is understood that these resources are freed when the object is
82garbage-collected, but since garbage collection is not guaranteed to happen,
83such objects also provide an explicit way to release the external resource,
84usually a :meth:`close` method. Programs are strongly recommended to explicitly
85close such objects. The ':keyword:`try`...\ :keyword:`finally`' statement
Nick Coghlan3a5d7e32008-08-31 12:40:14 +000086and the ':keyword:`with`' statement provide convenient ways to do this.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88.. index:: single: container
89
90Some objects contain references to other objects; these are called *containers*.
91Examples of containers are tuples, lists and dictionaries. The references are
92part of a container's value. In most cases, when we talk about the value of a
93container, we imply the values, not the identities of the contained objects;
94however, when we talk about the mutability of a container, only the identities
95of the immediately contained objects are implied. So, if an immutable container
96(like a tuple) contains a reference to a mutable object, its value changes if
97that mutable object is changed.
98
99Types affect almost all aspects of object behavior. Even the importance of
100object identity is affected in some sense: for immutable types, operations that
101compute new values may actually return a reference to any existing object with
102the same type and value, while for mutable objects this is not allowed. E.g.,
103after ``a = 1; b = 1``, ``a`` and ``b`` may or may not refer to the same object
104with the value one, depending on the implementation, but after ``c = []; d =
105[]``, ``c`` and ``d`` are guaranteed to refer to two different, unique, newly
106created empty lists. (Note that ``c = d = []`` assigns the same object to both
107``c`` and ``d``.)
108
109
110.. _types:
111
112The standard type hierarchy
113===========================
114
115.. index::
116 single: type
117 pair: data; type
118 pair: type; hierarchy
119 pair: extension; module
120 pair: C; language
121
122Below is a list of the types that are built into Python. Extension modules
123(written in C, Java, or other languages, depending on the implementation) can
124define additional types. Future versions of Python may add types to the type
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000125hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
126although such additions will often be provided via the standard library instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128.. index::
129 single: attribute
130 pair: special; attribute
131 triple: generic; special; attribute
132
133Some of the type descriptions below contain a paragraph listing 'special
134attributes.' These are attributes that provide access to the implementation and
135are not intended for general use. Their definition may change in the future.
136
137None
138 .. index:: object: None
139
140 This type has a single value. There is a single object with this value. This
141 object is accessed through the built-in name ``None``. It is used to signify the
142 absence of a value in many situations, e.g., it is returned from functions that
143 don't explicitly return anything. Its truth value is false.
144
145NotImplemented
146 .. index:: object: NotImplemented
147
148 This type has a single value. There is a single object with this value. This
149 object is accessed through the built-in name ``NotImplemented``. Numeric methods
150 and rich comparison methods may return this value if they do not implement the
151 operation for the operands provided. (The interpreter will then try the
152 reflected operation, or some other fallback, depending on the operator.) Its
153 truth value is true.
154
155Ellipsis
156 .. index:: object: Ellipsis
157
158 This type has a single value. There is a single object with this value. This
159 object is accessed through the literal ``...`` or the built-in name
160 ``Ellipsis``. Its truth value is true.
161
Christian Heimes072c0f12008-01-03 23:01:04 +0000162:class:`numbers.Number`
Georg Brandl116aa622007-08-15 14:28:22 +0000163 .. index:: object: numeric
164
165 These are created by numeric literals and returned as results by arithmetic
166 operators and arithmetic built-in functions. Numeric objects are immutable;
167 once created their value never changes. Python numbers are of course strongly
168 related to mathematical numbers, but subject to the limitations of numerical
169 representation in computers.
170
171 Python distinguishes between integers, floating point numbers, and complex
172 numbers:
173
Christian Heimes072c0f12008-01-03 23:01:04 +0000174 :class:`numbers.Integral`
Georg Brandl116aa622007-08-15 14:28:22 +0000175 .. index:: object: integer
176
177 These represent elements from the mathematical set of integers (positive and
178 negative).
179
Georg Brandl59d69162008-01-07 09:27:36 +0000180 There are two types of integers:
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000182 Integers (:class:`int`)
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Georg Brandl116aa622007-08-15 14:28:22 +0000184 These represent numbers in an unlimited range, subject to available (virtual)
185 memory only. For the purpose of shift and mask operations, a binary
186 representation is assumed, and negative numbers are represented in a variant of
187 2's complement which gives the illusion of an infinite string of sign bits
188 extending to the left.
189
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000190 Booleans (:class:`bool`)
Georg Brandl116aa622007-08-15 14:28:22 +0000191 .. index::
192 object: Boolean
193 single: False
194 single: True
195
196 These represent the truth values False and True. The two objects representing
197 the values False and True are the only Boolean objects. The Boolean type is a
Georg Brandl95817b32008-05-11 14:30:18 +0000198 subtype of the integer type, and Boolean values behave like the values 0 and 1,
Georg Brandl116aa622007-08-15 14:28:22 +0000199 respectively, in almost all contexts, the exception being that when converted to
200 a string, the strings ``"False"`` or ``"True"`` are returned, respectively.
201
202 .. index:: pair: integer; representation
203
204 The rules for integer representation are intended to give the most meaningful
Georg Brandlbb74a782008-05-11 10:53:16 +0000205 interpretation of shift and mask operations involving negative integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Christian Heimes072c0f12008-01-03 23:01:04 +0000207 :class:`numbers.Real` (:class:`float`)
Georg Brandl116aa622007-08-15 14:28:22 +0000208 .. index::
209 object: floating point
210 pair: floating point; number
211 pair: C; language
212 pair: Java; language
213
214 These represent machine-level double precision floating point numbers. You are
215 at the mercy of the underlying machine architecture (and C or Java
216 implementation) for the accepted range and handling of overflow. Python does not
217 support single-precision floating point numbers; the savings in processor and
218 memory usage that are usually the reason for using these is dwarfed by the
219 overhead of using objects in Python, so there is no reason to complicate the
220 language with two kinds of floating point numbers.
221
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000222 :class:`numbers.Complex` (:class:`complex`)
Georg Brandl116aa622007-08-15 14:28:22 +0000223 .. index::
224 object: complex
225 pair: complex; number
226
227 These represent complex numbers as a pair of machine-level double precision
228 floating point numbers. The same caveats apply as for floating point numbers.
229 The real and imaginary parts of a complex number ``z`` can be retrieved through
230 the read-only attributes ``z.real`` and ``z.imag``.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232Sequences
233 .. index::
234 builtin: len
235 object: sequence
236 single: index operation
237 single: item selection
238 single: subscription
239
240 These represent finite ordered sets indexed by non-negative numbers. The
241 built-in function :func:`len` returns the number of items of a sequence. When
242 the length of a sequence is *n*, the index set contains the numbers 0, 1,
243 ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``.
244
245 .. index:: single: slicing
246
247 Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such
248 that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a
249 sequence of the same type. This implies that the index set is renumbered so
250 that it starts at 0.
251
Georg Brandl116aa622007-08-15 14:28:22 +0000252 Some sequences also support "extended slicing" with a third "step" parameter:
253 ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n*
254 ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*.
255
256 Sequences are distinguished according to their mutability:
257
258 Immutable sequences
259 .. index::
260 object: immutable sequence
261 object: immutable
262
263 An object of an immutable sequence type cannot change once it is created. (If
264 the object contains references to other objects, these other objects may be
265 mutable and may be changed; however, the collection of objects directly
266 referenced by an immutable object cannot change.)
267
268 The following types are immutable sequences:
269
270 Strings
271 .. index::
272 builtin: chr
273 builtin: ord
Georg Brandldcc56f82007-08-31 16:41:12 +0000274 builtin: str
Georg Brandl116aa622007-08-15 14:28:22 +0000275 single: character
276 single: integer
277 single: Unicode
278
Ezio Melottif4d76e62011-10-25 09:23:42 +0300279 A string is a sequence of values that represent Unicode codepoints.
280 All the codepoints in range ``U+0000 - U+10FFFF`` can be represented
281 in a string. Python doesn't have a :c:type:`chr` type, and
Ezio Melottif7f0a662011-10-25 17:22:22 +0300282 every character in the string is represented as a string object
283 with length ``1``. The built-in function :func:`ord` converts a
284 character to its codepoint (as an integer); :func:`chr` converts
Ezio Melottif4d76e62011-10-25 09:23:42 +0300285 an integer in range ``0 - 10FFFF`` to the corresponding character.
286 :meth:`str.encode` can be used to convert a :class:`str` to
287 :class:`bytes` using the given encoding, and :meth:`bytes.decode` can
288 be used to achieve the opposite.
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 Tuples
291 .. index::
292 object: tuple
293 pair: singleton; tuple
294 pair: empty; tuple
295
Georg Brandldcc56f82007-08-31 16:41:12 +0000296 The items of a tuple are arbitrary Python objects. Tuples of two or
297 more items are formed by comma-separated lists of expressions. A tuple
298 of one item (a 'singleton') can be formed by affixing a comma to an
299 expression (an expression by itself does not create a tuple, since
300 parentheses must be usable for grouping of expressions). An empty
301 tuple can be formed by an empty pair of parentheses.
Georg Brandl116aa622007-08-15 14:28:22 +0000302
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000303 Bytes
304 .. index:: bytes, byte
305
306 A bytes object is an immutable array. The items are 8-bit bytes,
307 represented by integers in the range 0 <= x < 256. Bytes literals
308 (like ``b'abc'`` and the built-in function :func:`bytes` can be used to
309 construct bytes objects. Also, bytes objects can be decoded to strings
310 via the :meth:`decode` method.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312 Mutable sequences
313 .. index::
314 object: mutable sequence
315 object: mutable
316 pair: assignment; statement
317 single: delete
318 statement: del
319 single: subscription
320 single: slicing
321
322 Mutable sequences can be changed after they are created. The subscription and
323 slicing notations can be used as the target of assignment and :keyword:`del`
324 (delete) statements.
325
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000326 There are currently two intrinsic mutable sequence types:
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328 Lists
329 .. index:: object: list
330
Georg Brandldcc56f82007-08-31 16:41:12 +0000331 The items of a list are arbitrary Python objects. Lists are formed by
332 placing a comma-separated list of expressions in square brackets. (Note
333 that there are no special cases needed to form lists of length 0 or 1.)
334
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000335 Byte Arrays
336 .. index:: bytearray
Georg Brandldcc56f82007-08-31 16:41:12 +0000337
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000338 A bytearray object is a mutable array. They are created by the built-in
339 :func:`bytearray` constructor. Aside from being mutable (and hence
340 unhashable), byte arrays otherwise provide the same interface and
341 functionality as immutable bytes objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343 .. index:: module: array
344
Georg Brandldcc56f82007-08-31 16:41:12 +0000345 The extension module :mod:`array` provides an additional example of a
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000346 mutable sequence type, as does the :mod:`collections` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Georg Brandl116aa622007-08-15 14:28:22 +0000348Set types
349 .. index::
350 builtin: len
351 object: set type
352
353 These represent unordered, finite sets of unique, immutable objects. As such,
354 they cannot be indexed by any subscript. However, they can be iterated over, and
355 the built-in function :func:`len` returns the number of items in a set. Common
356 uses for sets are fast membership testing, removing duplicates from a sequence,
357 and computing mathematical operations such as intersection, union, difference,
358 and symmetric difference.
359
360 For set elements, the same immutability rules apply as for dictionary keys. Note
361 that numeric types obey the normal rules for numeric comparison: if two numbers
362 compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a
363 set.
364
365 There are currently two intrinsic set types:
366
367 Sets
368 .. index:: object: set
369
370 These represent a mutable set. They are created by the built-in :func:`set`
371 constructor and can be modified afterwards by several methods, such as
372 :meth:`add`.
373
374 Frozen sets
375 .. index:: object: frozenset
376
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000377 These represent an immutable set. They are created by the built-in
378 :func:`frozenset` constructor. As a frozenset is immutable and
379 :term:`hashable`, it can be used again as an element of another set, or as
380 a dictionary key.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Georg Brandl116aa622007-08-15 14:28:22 +0000382Mappings
383 .. index::
384 builtin: len
385 single: subscription
386 object: mapping
387
388 These represent finite sets of objects indexed by arbitrary index sets. The
389 subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping
390 ``a``; this can be used in expressions and as the target of assignments or
391 :keyword:`del` statements. The built-in function :func:`len` returns the number
392 of items in a mapping.
393
394 There is currently a single intrinsic mapping type:
395
396 Dictionaries
397 .. index:: object: dictionary
398
399 These represent finite sets of objects indexed by nearly arbitrary values. The
400 only types of values not acceptable as keys are values containing lists or
401 dictionaries or other mutable types that are compared by value rather than by
402 object identity, the reason being that the efficient implementation of
403 dictionaries requires a key's hash value to remain constant. Numeric types used
404 for keys obey the normal rules for numeric comparison: if two numbers compare
405 equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index
406 the same dictionary entry.
407
408 Dictionaries are mutable; they can be created by the ``{...}`` notation (see
409 section :ref:`dict`).
410
411 .. index::
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000412 module: dbm.ndbm
413 module: dbm.gnu
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Benjamin Peterson9a46cab2008-09-08 02:49:30 +0000415 The extension modules :mod:`dbm.ndbm` and :mod:`dbm.gnu` provide
416 additional examples of mapping types, as does the :mod:`collections`
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000417 module.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Georg Brandl116aa622007-08-15 14:28:22 +0000419Callable types
420 .. index::
421 object: callable
422 pair: function; call
423 single: invocation
424 pair: function; argument
425
426 These are the types to which the function call operation (see section
427 :ref:`calls`) can be applied:
428
429 User-defined functions
430 .. index::
431 pair: user-defined; function
432 object: function
433 object: user-defined function
434
435 A user-defined function object is created by a function definition (see
436 section :ref:`function`). It should be called with an argument list
437 containing the same number of items as the function's formal parameter
438 list.
439
440 Special attributes:
441
442 +-------------------------+-------------------------------+-----------+
443 | Attribute | Meaning | |
444 +=========================+===============================+===========+
445 | :attr:`__doc__` | The function's documentation | Writable |
446 | | string, or ``None`` if | |
447 | | unavailable | |
448 +-------------------------+-------------------------------+-----------+
449 | :attr:`__name__` | The function's name | Writable |
450 +-------------------------+-------------------------------+-----------+
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100451 | :attr:`__qualname__` | The function's | Writable |
452 | | :term:`qualified name` | |
453 | | | |
454 | | .. versionadded:: 3.3 | |
455 +-------------------------+-------------------------------+-----------+
Georg Brandl116aa622007-08-15 14:28:22 +0000456 | :attr:`__module__` | The name of the module the | Writable |
457 | | function was defined in, or | |
458 | | ``None`` if unavailable. | |
459 +-------------------------+-------------------------------+-----------+
460 | :attr:`__defaults__` | A tuple containing default | Writable |
461 | | argument values for those | |
462 | | arguments that have defaults, | |
463 | | or ``None`` if no arguments | |
464 | | have a default value | |
465 +-------------------------+-------------------------------+-----------+
466 | :attr:`__code__` | The code object representing | Writable |
467 | | the compiled function body. | |
468 +-------------------------+-------------------------------+-----------+
469 | :attr:`__globals__` | A reference to the dictionary | Read-only |
470 | | that holds the function's | |
471 | | global variables --- the | |
472 | | global namespace of the | |
473 | | module in which the function | |
474 | | was defined. | |
475 +-------------------------+-------------------------------+-----------+
476 | :attr:`__dict__` | The namespace supporting | Writable |
477 | | arbitrary function | |
478 | | attributes. | |
479 +-------------------------+-------------------------------+-----------+
480 | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only |
481 | | that contain bindings for the | |
482 | | function's free variables. | |
483 +-------------------------+-------------------------------+-----------+
484 | :attr:`__annotations__` | A dict containing annotations | Writable |
485 | | of parameters. The keys of | |
486 | | the dict are the parameter | |
487 | | names, or ``'return'`` for | |
488 | | the return annotation, if | |
489 | | provided. | |
490 +-------------------------+-------------------------------+-----------+
491 | :attr:`__kwdefaults__` | A dict containing defaults | Writable |
492 | | for keyword-only parameters. | |
493 +-------------------------+-------------------------------+-----------+
494
495 Most of the attributes labelled "Writable" check the type of the assigned value.
496
Georg Brandl116aa622007-08-15 14:28:22 +0000497 Function objects also support getting and setting arbitrary attributes, which
498 can be used, for example, to attach metadata to functions. Regular attribute
499 dot-notation is used to get and set such attributes. *Note that the current
500 implementation only supports function attributes on user-defined functions.
501 Function attributes on built-in functions may be supported in the future.*
502
503 Additional information about a function's definition can be retrieved from its
504 code object; see the description of internal types below.
505
506 .. index::
507 single: __doc__ (function attribute)
508 single: __name__ (function attribute)
509 single: __module__ (function attribute)
510 single: __dict__ (function attribute)
511 single: __defaults__ (function attribute)
512 single: __closure__ (function attribute)
513 single: __code__ (function attribute)
514 single: __globals__ (function attribute)
515 single: __annotations__ (function attribute)
516 single: __kwdefaults__ (function attribute)
517 pair: global; namespace
518
Georg Brandl2e0b7552007-11-27 12:43:08 +0000519 Instance methods
Georg Brandl116aa622007-08-15 14:28:22 +0000520 .. index::
521 object: method
522 object: user-defined method
523 pair: user-defined; method
524
Georg Brandl2e0b7552007-11-27 12:43:08 +0000525 An instance method object combines a class, a class instance and any
526 callable object (normally a user-defined function).
527
528 .. index::
529 single: __func__ (method attribute)
530 single: __self__ (method attribute)
531 single: __doc__ (method attribute)
532 single: __name__ (method attribute)
533 single: __module__ (method attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Christian Heimesff737952007-11-27 10:40:20 +0000535 Special read-only attributes: :attr:`__self__` is the class instance object,
536 :attr:`__func__` is the function object; :attr:`__doc__` is the method's
537 documentation (same as ``__func__.__doc__``); :attr:`__name__` is the
538 method name (same as ``__func__.__name__``); :attr:`__module__` is the
539 name of the module the method was defined in, or ``None`` if unavailable.
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandl116aa622007-08-15 14:28:22 +0000541 Methods also support accessing (but not setting) the arbitrary function
542 attributes on the underlying function object.
543
Georg Brandl2e0b7552007-11-27 12:43:08 +0000544 User-defined method objects may be created when getting an attribute of a
545 class (perhaps via an instance of that class), if that attribute is a
546 user-defined function object or a class method object.
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000547
Georg Brandl2e0b7552007-11-27 12:43:08 +0000548 When an instance method object is created by retrieving a user-defined
549 function object from a class via one of its instances, its
550 :attr:`__self__` attribute is the instance, and the method object is said
551 to be bound. The new method's :attr:`__func__` attribute is the original
552 function object.
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Georg Brandl2e0b7552007-11-27 12:43:08 +0000554 When a user-defined method object is created by retrieving another method
555 object from a class or instance, the behaviour is the same as for a
556 function object, except that the :attr:`__func__` attribute of the new
557 instance is not the original method object but its :attr:`__func__`
558 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Georg Brandl2e0b7552007-11-27 12:43:08 +0000560 When an instance method object is created by retrieving a class method
561 object from a class or instance, its :attr:`__self__` attribute is the
562 class itself, and its :attr:`__func__` attribute is the function object
563 underlying the class method.
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Georg Brandl2e0b7552007-11-27 12:43:08 +0000565 When an instance method object is called, the underlying function
566 (:attr:`__func__`) is called, inserting the class instance
567 (:attr:`__self__`) in front of the argument list. For instance, when
568 :class:`C` is a class which contains a definition for a function
569 :meth:`f`, and ``x`` is an instance of :class:`C`, calling ``x.f(1)`` is
570 equivalent to calling ``C.f(x, 1)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000571
Georg Brandl2e0b7552007-11-27 12:43:08 +0000572 When an instance method object is derived from a class method object, the
573 "class instance" stored in :attr:`__self__` will actually be the class
574 itself, so that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to
575 calling ``f(C,1)`` where ``f`` is the underlying function.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Georg Brandl2e0b7552007-11-27 12:43:08 +0000577 Note that the transformation from function object to instance method
578 object happens each time the attribute is retrieved from the instance. In
579 some cases, a fruitful optimization is to assign the attribute to a local
580 variable and call that local variable. Also notice that this
581 transformation only happens for user-defined functions; other callable
582 objects (and all non-callable objects) are retrieved without
583 transformation. It is also important to note that user-defined functions
584 which are attributes of a class instance are not converted to bound
585 methods; this *only* happens when the function is an attribute of the
586 class.
Georg Brandl116aa622007-08-15 14:28:22 +0000587
588 Generator functions
589 .. index::
590 single: generator; function
591 single: generator; iterator
592
593 A function or method which uses the :keyword:`yield` statement (see section
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000594 :ref:`yield`) is called a :dfn:`generator function`. Such a function, when
595 called, always returns an iterator object which can be used to execute the
596 body of the function: calling the iterator's :meth:`__next__` method will
597 cause the function to execute until it provides a value using the
598 :keyword:`yield` statement. When the function executes a
Georg Brandl116aa622007-08-15 14:28:22 +0000599 :keyword:`return` statement or falls off the end, a :exc:`StopIteration`
600 exception is raised and the iterator will have reached the end of the set of
601 values to be returned.
602
603 Built-in functions
604 .. index::
605 object: built-in function
606 object: function
607 pair: C; language
608
609 A built-in function object is a wrapper around a C function. Examples of
610 built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
611 standard built-in module). The number and type of the arguments are
612 determined by the C function. Special read-only attributes:
613 :attr:`__doc__` is the function's documentation string, or ``None`` if
614 unavailable; :attr:`__name__` is the function's name; :attr:`__self__` is
615 set to ``None`` (but see the next item); :attr:`__module__` is the name of
616 the module the function was defined in or ``None`` if unavailable.
617
618 Built-in methods
619 .. index::
620 object: built-in method
621 object: method
622 pair: built-in; method
623
624 This is really a different disguise of a built-in function, this time containing
625 an object passed to the C function as an implicit extra argument. An example of
626 a built-in method is ``alist.append()``, assuming *alist* is a list object. In
627 this case, the special read-only attribute :attr:`__self__` is set to the object
Éric Araujoc9562f32010-12-26 02:18:49 +0000628 denoted by *alist*.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Georg Brandl85eb8c12007-08-31 16:33:38 +0000630 Classes
631 Classes are callable. These objects normally act as factories for new
632 instances of themselves, but variations are possible for class types that
633 override :meth:`__new__`. The arguments of the call are passed to
634 :meth:`__new__` and, in the typical case, to :meth:`__init__` to
635 initialize the new instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Georg Brandl85eb8c12007-08-31 16:33:38 +0000637 Class Instances
638 Instances of arbitrary classes can be made callable by defining a
639 :meth:`__call__` method in their class.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Georg Brandl116aa622007-08-15 14:28:22 +0000641
642Modules
643 .. index::
644 statement: import
645 object: module
646
647 Modules are imported by the :keyword:`import` statement (see section
648 :ref:`import`). A module object has a
649 namespace implemented by a dictionary object (this is the dictionary referenced
650 by the __globals__ attribute of functions defined in the module). Attribute
651 references are translated to lookups in this dictionary, e.g., ``m.x`` is
652 equivalent to ``m.__dict__["x"]``. A module object does not contain the code
653 object used to initialize the module (since it isn't needed once the
654 initialization is done).
655
Georg Brandl116aa622007-08-15 14:28:22 +0000656 Attribute assignment updates the module's namespace dictionary, e.g., ``m.x =
657 1`` is equivalent to ``m.__dict__["x"] = 1``.
658
659 .. index:: single: __dict__ (module attribute)
660
661 Special read-only attribute: :attr:`__dict__` is the module's namespace as a
662 dictionary object.
663
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000664 .. impl-detail::
665
666 Because of the way CPython clears module dictionaries, the module
667 dictionary will be cleared when the module falls out of scope even if the
668 dictionary still has live references. To avoid this, copy the dictionary
669 or keep the module around while using its dictionary directly.
670
Georg Brandl116aa622007-08-15 14:28:22 +0000671 .. index::
672 single: __name__ (module attribute)
673 single: __doc__ (module attribute)
674 single: __file__ (module attribute)
675 pair: module; namespace
676
677 Predefined (writable) attributes: :attr:`__name__` is the module's name;
678 :attr:`__doc__` is the module's documentation string, or ``None`` if
679 unavailable; :attr:`__file__` is the pathname of the file from which the module
680 was loaded, if it was loaded from a file. The :attr:`__file__` attribute is not
681 present for C modules that are statically linked into the interpreter; for
682 extension modules loaded dynamically from a shared library, it is the pathname
683 of the shared library file.
684
Georg Brandl85eb8c12007-08-31 16:33:38 +0000685Custom classes
Georg Brandl5dbb84a2009-09-02 20:31:26 +0000686 Custom class types are typically created by class definitions (see section
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000687 :ref:`class`). A class has a namespace implemented by a dictionary object.
688 Class attribute references are translated to lookups in this dictionary, e.g.,
689 ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of
690 hooks which allow for other means of locating attributes). When the attribute
691 name is not found there, the attribute search continues in the base classes.
692 This search of the base classes uses the C3 method resolution order which
693 behaves correctly even in the presence of 'diamond' inheritance structures
694 where there are multiple inheritance paths leading back to a common ancestor.
695 Additional details on the C3 MRO used by Python can be found in the
696 documentation accompanying the 2.3 release at
697 http://www.python.org/download/releases/2.3/mro/.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Nick Coghlan3a5d7e32008-08-31 12:40:14 +0000699 .. XXX: Could we add that MRO doc as an appendix to the language ref?
Georg Brandl85eb8c12007-08-31 16:33:38 +0000700
Georg Brandl116aa622007-08-15 14:28:22 +0000701 .. index::
702 object: class
703 object: class instance
704 object: instance
705 pair: class object; call
706 single: container
707 object: dictionary
708 pair: class; attribute
709
710 When a class attribute reference (for class :class:`C`, say) would yield a
Georg Brandl2e0b7552007-11-27 12:43:08 +0000711 class method object, it is transformed into an instance method object whose
712 :attr:`__self__` attributes is :class:`C`. When it would yield a static
713 method object, it is transformed into the object wrapped by the static method
714 object. See section :ref:`descriptors` for another way in which attributes
715 retrieved from a class may differ from those actually contained in its
716 :attr:`__dict__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 .. index:: triple: class; attribute; assignment
719
720 Class attribute assignments update the class's dictionary, never the dictionary
721 of a base class.
722
723 .. index:: pair: class object; call
724
725 A class object can be called (see above) to yield a class instance (see below).
726
727 .. index::
728 single: __name__ (class attribute)
729 single: __module__ (class attribute)
730 single: __dict__ (class attribute)
731 single: __bases__ (class attribute)
732 single: __doc__ (class attribute)
733
734 Special attributes: :attr:`__name__` is the class name; :attr:`__module__` is
735 the module name in which the class was defined; :attr:`__dict__` is the
736 dictionary containing the class's namespace; :attr:`__bases__` is a tuple
737 (possibly empty or a singleton) containing the base classes, in the order of
738 their occurrence in the base class list; :attr:`__doc__` is the class's
739 documentation string, or None if undefined.
740
741Class instances
742 .. index::
743 object: class instance
744 object: instance
745 pair: class; instance
746 pair: class instance; attribute
747
Georg Brandl2e0b7552007-11-27 12:43:08 +0000748 A class instance is created by calling a class object (see above). A class
749 instance has a namespace implemented as a dictionary which is the first place
750 in which attribute references are searched. When an attribute is not found
751 there, and the instance's class has an attribute by that name, the search
752 continues with the class attributes. If a class attribute is found that is a
753 user-defined function object, it is transformed into an instance method
754 object whose :attr:`__self__` attribute is the instance. Static method and
755 class method objects are also transformed; see above under "Classes". See
756 section :ref:`descriptors` for another way in which attributes of a class
757 retrieved via its instances may differ from the objects actually stored in
758 the class's :attr:`__dict__`. If no class attribute is found, and the
759 object's class has a :meth:`__getattr__` method, that is called to satisfy
760 the lookup.
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762 .. index:: triple: class instance; attribute; assignment
763
764 Attribute assignments and deletions update the instance's dictionary, never a
765 class's dictionary. If the class has a :meth:`__setattr__` or
766 :meth:`__delattr__` method, this is called instead of updating the instance
767 dictionary directly.
768
769 .. index::
770 object: numeric
771 object: sequence
772 object: mapping
773
774 Class instances can pretend to be numbers, sequences, or mappings if they have
775 methods with certain special names. See section :ref:`specialnames`.
776
777 .. index::
778 single: __dict__ (instance attribute)
779 single: __class__ (instance attribute)
780
781 Special attributes: :attr:`__dict__` is the attribute dictionary;
782 :attr:`__class__` is the instance's class.
783
Antoine Pitrou4adb2882010-01-04 18:50:53 +0000784I/O objects (also known as file objects)
Georg Brandl116aa622007-08-15 14:28:22 +0000785 .. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000786 builtin: open
Antoine Pitrou4adb2882010-01-04 18:50:53 +0000787 module: io
Georg Brandl116aa622007-08-15 14:28:22 +0000788 single: popen() (in module os)
789 single: makefile() (socket method)
790 single: sys.stdin
791 single: sys.stdout
792 single: sys.stderr
793 single: stdio
794 single: stdin (in module sys)
795 single: stdout (in module sys)
796 single: stderr (in module sys)
797
Antoine Pitrou0b65b0f2010-09-15 09:58:26 +0000798 A :term:`file object` represents an open file. Various shortcuts are
799 available to create file objects: the :func:`open` built-in function, and
800 also :func:`os.popen`, :func:`os.fdopen`, and the :meth:`makefile` method
Antoine Pitrou4adb2882010-01-04 18:50:53 +0000801 of socket objects (and perhaps by other functions or methods provided
802 by extension modules).
803
804 The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are
805 initialized to file objects corresponding to the interpreter's standard
806 input, output and error streams; they are all open in text mode and
807 therefore follow the interface defined by the :class:`io.TextIOBase`
808 abstract class.
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810Internal types
811 .. index::
812 single: internal type
813 single: types, internal
814
815 A few types used internally by the interpreter are exposed to the user. Their
816 definitions may change with future versions of the interpreter, but they are
817 mentioned here for completeness.
818
819 Code objects
820 .. index::
821 single: bytecode
822 object: code
823
Georg Brandl9afde1c2007-11-01 20:32:30 +0000824 Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
Georg Brandl116aa622007-08-15 14:28:22 +0000825 The difference between a code object and a function object is that the function
826 object contains an explicit reference to the function's globals (the module in
827 which it was defined), while a code object contains no context; also the default
828 argument values are stored in the function object, not in the code object
829 (because they represent values calculated at run-time). Unlike function
830 objects, code objects are immutable and contain no references (directly or
831 indirectly) to mutable objects.
832
Senthil Kumaran7cafd262010-10-02 03:16:04 +0000833 .. index::
834 single: co_argcount (code object attribute)
835 single: co_code (code object attribute)
836 single: co_consts (code object attribute)
837 single: co_filename (code object attribute)
838 single: co_firstlineno (code object attribute)
839 single: co_flags (code object attribute)
840 single: co_lnotab (code object attribute)
841 single: co_name (code object attribute)
842 single: co_names (code object attribute)
843 single: co_nlocals (code object attribute)
844 single: co_stacksize (code object attribute)
845 single: co_varnames (code object attribute)
846 single: co_cellvars (code object attribute)
847 single: co_freevars (code object attribute)
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849 Special read-only attributes: :attr:`co_name` gives the function name;
850 :attr:`co_argcount` is the number of positional arguments (including arguments
851 with default values); :attr:`co_nlocals` is the number of local variables used
852 by the function (including arguments); :attr:`co_varnames` is a tuple containing
853 the names of the local variables (starting with the argument names);
854 :attr:`co_cellvars` is a tuple containing the names of local variables that are
855 referenced by nested functions; :attr:`co_freevars` is a tuple containing the
856 names of free variables; :attr:`co_code` is a string representing the sequence
857 of bytecode instructions; :attr:`co_consts` is a tuple containing the literals
858 used by the bytecode; :attr:`co_names` is a tuple containing the names used by
859 the bytecode; :attr:`co_filename` is the filename from which the code was
860 compiled; :attr:`co_firstlineno` is the first line number of the function;
Georg Brandl9afde1c2007-11-01 20:32:30 +0000861 :attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to
Georg Brandl116aa622007-08-15 14:28:22 +0000862 line numbers (for details see the source code of the interpreter);
863 :attr:`co_stacksize` is the required stack size (including local variables);
864 :attr:`co_flags` is an integer encoding a number of flags for the interpreter.
865
Georg Brandl116aa622007-08-15 14:28:22 +0000866 .. index:: object: generator
867
868 The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is set if
869 the function uses the ``*arguments`` syntax to accept an arbitrary number of
870 positional arguments; bit ``0x08`` is set if the function uses the
871 ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set
872 if the function is a generator.
873
874 Future feature declarations (``from __future__ import division``) also use bits
875 in :attr:`co_flags` to indicate whether a code object was compiled with a
876 particular feature enabled: bit ``0x2000`` is set if the function was compiled
877 with future division enabled; bits ``0x10`` and ``0x1000`` were used in earlier
878 versions of Python.
879
880 Other bits in :attr:`co_flags` are reserved for internal use.
881
882 .. index:: single: documentation string
883
884 If a code object represents a function, the first item in :attr:`co_consts` is
885 the documentation string of the function, or ``None`` if undefined.
886
Georg Brandla6053b42009-09-01 08:11:14 +0000887 .. _frame-objects:
888
Georg Brandl116aa622007-08-15 14:28:22 +0000889 Frame objects
890 .. index:: object: frame
891
892 Frame objects represent execution frames. They may occur in traceback objects
893 (see below).
894
895 .. index::
896 single: f_back (frame attribute)
897 single: f_code (frame attribute)
898 single: f_globals (frame attribute)
899 single: f_locals (frame attribute)
900 single: f_lasti (frame attribute)
901 single: f_builtins (frame attribute)
902
903 Special read-only attributes: :attr:`f_back` is to the previous stack frame
904 (towards the caller), or ``None`` if this is the bottom stack frame;
905 :attr:`f_code` is the code object being executed in this frame; :attr:`f_locals`
906 is the dictionary used to look up local variables; :attr:`f_globals` is used for
907 global variables; :attr:`f_builtins` is used for built-in (intrinsic) names;
908 :attr:`f_lasti` gives the precise instruction (this is an index into the
909 bytecode string of the code object).
910
911 .. index::
912 single: f_trace (frame attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000913 single: f_lineno (frame attribute)
914
915 Special writable attributes: :attr:`f_trace`, if not ``None``, is a function
916 called at the start of each source code line (this is used by the debugger);
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000917 :attr:`f_lineno` is the current line number of the frame --- writing to this
918 from within a trace function jumps to the given line (only for the bottom-most
919 frame). A debugger can implement a Jump command (aka Set Next Statement)
920 by writing to f_lineno.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922 Traceback objects
923 .. index::
924 object: traceback
925 pair: stack; trace
926 pair: exception; handler
927 pair: execution; stack
928 single: exc_info (in module sys)
Georg Brandl116aa622007-08-15 14:28:22 +0000929 single: last_traceback (in module sys)
930 single: sys.exc_info
931 single: sys.last_traceback
932
933 Traceback objects represent a stack trace of an exception. A traceback object
934 is created when an exception occurs. When the search for an exception handler
935 unwinds the execution stack, at each unwound level a traceback object is
936 inserted in front of the current traceback. When an exception handler is
937 entered, the stack trace is made available to the program. (See section
938 :ref:`try`.) It is accessible as the third item of the
939 tuple returned by ``sys.exc_info()``. When the program contains no suitable
940 handler, the stack trace is written (nicely formatted) to the standard error
941 stream; if the interpreter is interactive, it is also made available to the user
942 as ``sys.last_traceback``.
943
944 .. index::
945 single: tb_next (traceback attribute)
946 single: tb_frame (traceback attribute)
947 single: tb_lineno (traceback attribute)
948 single: tb_lasti (traceback attribute)
949 statement: try
950
951 Special read-only attributes: :attr:`tb_next` is the next level in the stack
952 trace (towards the frame where the exception occurred), or ``None`` if there is
953 no next level; :attr:`tb_frame` points to the execution frame of the current
954 level; :attr:`tb_lineno` gives the line number where the exception occurred;
955 :attr:`tb_lasti` indicates the precise instruction. The line number and last
956 instruction in the traceback may differ from the line number of its frame object
957 if the exception occurred in a :keyword:`try` statement with no matching except
958 clause or with a finally clause.
959
960 Slice objects
961 .. index:: builtin: slice
962
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000963 Slice objects are used to represent slices for :meth:`__getitem__`
964 methods. They are also created by the built-in :func:`slice` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966 .. index::
967 single: start (slice object attribute)
968 single: stop (slice object attribute)
969 single: step (slice object attribute)
970
971 Special read-only attributes: :attr:`start` is the lower bound; :attr:`stop` is
972 the upper bound; :attr:`step` is the step value; each is ``None`` if omitted.
973 These attributes can have any type.
974
975 Slice objects support one method:
976
Georg Brandl116aa622007-08-15 14:28:22 +0000977 .. method:: slice.indices(self, length)
978
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000979 This method takes a single integer argument *length* and computes
980 information about the slice that the slice object would describe if
981 applied to a sequence of *length* items. It returns a tuple of three
982 integers; respectively these are the *start* and *stop* indices and the
983 *step* or stride length of the slice. Missing or out-of-bounds indices
984 are handled in a manner consistent with regular slices.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Georg Brandl116aa622007-08-15 14:28:22 +0000986 Static method objects
987 Static method objects provide a way of defeating the transformation of function
988 objects to method objects described above. A static method object is a wrapper
989 around any other object, usually a user-defined method object. When a static
990 method object is retrieved from a class or a class instance, the object actually
991 returned is the wrapped object, which is not subject to any further
992 transformation. Static method objects are not themselves callable, although the
993 objects they wrap usually are. Static method objects are created by the built-in
994 :func:`staticmethod` constructor.
995
996 Class method objects
997 A class method object, like a static method object, is a wrapper around another
998 object that alters the way in which that object is retrieved from classes and
999 class instances. The behaviour of class method objects upon such retrieval is
1000 described above, under "User-defined methods". Class method objects are created
1001 by the built-in :func:`classmethod` constructor.
1002
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandl116aa622007-08-15 14:28:22 +00001004.. _specialnames:
1005
1006Special method names
1007====================
1008
1009.. index::
1010 pair: operator; overloading
1011 single: __getitem__() (mapping object method)
1012
1013A class can implement certain operations that are invoked by special syntax
1014(such as arithmetic operations or subscripting and slicing) by defining methods
1015with special names. This is Python's approach to :dfn:`operator overloading`,
1016allowing classes to define their own behavior with respect to language
1017operators. For instance, if a class defines a method named :meth:`__getitem__`,
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00001018and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
1019to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an
1020operation raise an exception when no appropriate method is defined (typically
1021:exc:`AttributeError` or :exc:`TypeError`).
Georg Brandl65ea9bd2007-09-05 13:36:27 +00001022
Georg Brandl116aa622007-08-15 14:28:22 +00001023When implementing a class that emulates any built-in type, it is important that
1024the emulation only be implemented to the degree that it makes sense for the
1025object being modelled. For example, some sequences may work well with retrieval
1026of individual elements, but extracting a slice may not make sense. (One example
1027of this is the :class:`NodeList` interface in the W3C's Document Object Model.)
1028
1029
1030.. _customization:
1031
1032Basic customization
1033-------------------
1034
Georg Brandl116aa622007-08-15 14:28:22 +00001035.. method:: object.__new__(cls[, ...])
1036
Georg Brandlaf265f42008-12-07 15:06:20 +00001037 .. index:: pair: subclassing; immutable types
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039 Called to create a new instance of class *cls*. :meth:`__new__` is a static
1040 method (special-cased so you need not declare it as such) that takes the class
1041 of which an instance was requested as its first argument. The remaining
1042 arguments are those passed to the object constructor expression (the call to the
1043 class). The return value of :meth:`__new__` should be the new object instance
1044 (usually an instance of *cls*).
1045
1046 Typical implementations create a new instance of the class by invoking the
1047 superclass's :meth:`__new__` method using ``super(currentclass,
1048 cls).__new__(cls[, ...])`` with appropriate arguments and then modifying the
1049 newly-created instance as necessary before returning it.
1050
1051 If :meth:`__new__` returns an instance of *cls*, then the new instance's
1052 :meth:`__init__` method will be invoked like ``__init__(self[, ...])``, where
1053 *self* is the new instance and the remaining arguments are the same as were
1054 passed to :meth:`__new__`.
1055
1056 If :meth:`__new__` does not return an instance of *cls*, then the new instance's
1057 :meth:`__init__` method will not be invoked.
1058
1059 :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
Christian Heimes790c8232008-01-07 21:14:23 +00001060 int, str, or tuple) to customize instance creation. It is also commonly
1061 overridden in custom metaclasses in order to customize class creation.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
1063
1064.. method:: object.__init__(self[, ...])
1065
1066 .. index:: pair: class; constructor
1067
1068 Called when the instance is created. The arguments are those passed to the
1069 class constructor expression. If a base class has an :meth:`__init__` method,
1070 the derived class's :meth:`__init__` method, if any, must explicitly call it to
1071 ensure proper initialization of the base class part of the instance; for
1072 example: ``BaseClass.__init__(self, [args...])``. As a special constraint on
1073 constructors, no value may be returned; doing so will cause a :exc:`TypeError`
1074 to be raised at runtime.
1075
1076
1077.. method:: object.__del__(self)
1078
1079 .. index::
1080 single: destructor
1081 statement: del
1082
1083 Called when the instance is about to be destroyed. This is also called a
1084 destructor. If a base class has a :meth:`__del__` method, the derived class's
1085 :meth:`__del__` method, if any, must explicitly call it to ensure proper
1086 deletion of the base class part of the instance. Note that it is possible
1087 (though not recommended!) for the :meth:`__del__` method to postpone destruction
1088 of the instance by creating a new reference to it. It may then be called at a
1089 later time when this new reference is deleted. It is not guaranteed that
1090 :meth:`__del__` methods are called for objects that still exist when the
1091 interpreter exits.
1092
1093 .. note::
1094
1095 ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
1096 the reference count for ``x`` by one, and the latter is only called when
1097 ``x``'s reference count reaches zero. Some common situations that may
1098 prevent the reference count of an object from going to zero include:
1099 circular references between objects (e.g., a doubly-linked list or a tree
1100 data structure with parent and child pointers); a reference to the object
1101 on the stack frame of a function that caught an exception (the traceback
1102 stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or a
1103 reference to the object on the stack frame that raised an unhandled
1104 exception in interactive mode (the traceback stored in
1105 ``sys.last_traceback`` keeps the stack frame alive). The first situation
1106 can only be remedied by explicitly breaking the cycles; the latter two
1107 situations can be resolved by storing ``None`` in ``sys.last_traceback``.
1108 Circular references which are garbage are detected when the option cycle
1109 detector is enabled (it's on by default), but can only be cleaned up if
1110 there are no Python- level :meth:`__del__` methods involved. Refer to the
1111 documentation for the :mod:`gc` module for more information about how
1112 :meth:`__del__` methods are handled by the cycle detector, particularly
1113 the description of the ``garbage`` value.
1114
1115 .. warning::
1116
1117 Due to the precarious circumstances under which :meth:`__del__` methods are
1118 invoked, exceptions that occur during their execution are ignored, and a warning
1119 is printed to ``sys.stderr`` instead. Also, when :meth:`__del__` is invoked in
1120 response to a module being deleted (e.g., when execution of the program is
1121 done), other globals referenced by the :meth:`__del__` method may already have
Brett Cannone1327f72009-01-29 04:10:21 +00001122 been deleted or in the process of being torn down (e.g. the import
1123 machinery shutting down). For this reason, :meth:`__del__` methods
1124 should do the absolute
Georg Brandl116aa622007-08-15 14:28:22 +00001125 minimum needed to maintain external invariants. Starting with version 1.5,
1126 Python guarantees that globals whose name begins with a single underscore are
1127 deleted from their module before other globals are deleted; if no other
1128 references to such globals exist, this may help in assuring that imported
1129 modules are still available at the time when the :meth:`__del__` method is
1130 called.
1131
1132
1133.. method:: object.__repr__(self)
1134
1135 .. index:: builtin: repr
1136
Benjamin Peterson1c9313f2008-10-12 12:51:12 +00001137 Called by the :func:`repr` built-in function to compute the "official" string
1138 representation of an object. If at all possible, this should look like a
1139 valid Python expression that could be used to recreate an object with the
1140 same value (given an appropriate environment). If this is not possible, a
1141 string of the form ``<...some useful description...>`` should be returned.
1142 The return value must be a string object. If a class defines :meth:`__repr__`
1143 but not :meth:`__str__`, then :meth:`__repr__` is also used when an
1144 "informal" string representation of instances of that class is required.
Georg Brandl116aa622007-08-15 14:28:22 +00001145
Georg Brandl116aa622007-08-15 14:28:22 +00001146 This is typically used for debugging, so it is important that the representation
1147 is information-rich and unambiguous.
1148
1149
1150.. method:: object.__str__(self)
1151
1152 .. index::
1153 builtin: str
Georg Brandl4b491312007-08-31 09:22:56 +00001154 builtin: print
Georg Brandl116aa622007-08-15 14:28:22 +00001155
Georg Brandldcc56f82007-08-31 16:41:12 +00001156 Called by the :func:`str` built-in function and by the :func:`print` function
1157 to compute the "informal" string representation of an object. This differs
1158 from :meth:`__repr__` in that it does not have to be a valid Python
Georg Brandl116aa622007-08-15 14:28:22 +00001159 expression: a more convenient or concise representation may be used instead.
1160 The return value must be a string object.
1161
Georg Brandldcc56f82007-08-31 16:41:12 +00001162 .. XXX what about subclasses of string?
1163
Georg Brandl116aa622007-08-15 14:28:22 +00001164
Benjamin Peterson1fafc1a2011-10-25 00:03:51 -04001165.. method:: object.__bytes__(self)
1166
1167 .. index:: builtin: bytes
1168
1169 Called by :func:`bytes` to compute a byte-string representation of an
1170 object. This should return a ``bytes`` object.
1171
1172
Georg Brandl4b491312007-08-31 09:22:56 +00001173.. method:: object.__format__(self, format_spec)
1174
1175 .. index::
1176 pair: string; conversion
1177 builtin: str
1178 builtin: print
1179
1180 Called by the :func:`format` built-in function (and by extension, the
1181 :meth:`format` method of class :class:`str`) to produce a "formatted"
1182 string representation of an object. The ``format_spec`` argument is
1183 a string that contains a description of the formatting options desired.
1184 The interpretation of the ``format_spec`` argument is up to the type
1185 implementing :meth:`__format__`, however most classes will either
1186 delegate formatting to one of the built-in types, or use a similar
1187 formatting option syntax.
Georg Brandl48310cd2009-01-03 21:18:54 +00001188
Georg Brandl4b491312007-08-31 09:22:56 +00001189 See :ref:`formatspec` for a description of the standard formatting syntax.
1190
1191 The return value must be a string object.
1192
1193
Georg Brandl33413cb2009-03-31 19:06:37 +00001194.. _richcmpfuncs:
Georg Brandl116aa622007-08-15 14:28:22 +00001195.. method:: object.__lt__(self, other)
1196 object.__le__(self, other)
1197 object.__eq__(self, other)
1198 object.__ne__(self, other)
1199 object.__gt__(self, other)
1200 object.__ge__(self, other)
1201
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001202 .. index::
1203 single: comparisons
1204
Georg Brandl05f5ab72008-09-24 09:11:47 +00001205 These are the so-called "rich comparison" methods. The correspondence between
Georg Brandl116aa622007-08-15 14:28:22 +00001206 operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
1207 ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls
1208 ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls
1209 ``x.__ge__(y)``.
1210
1211 A rich comparison method may return the singleton ``NotImplemented`` if it does
1212 not implement the operation for a given pair of arguments. By convention,
1213 ``False`` and ``True`` are returned for a successful comparison. However, these
1214 methods can return any value, so if the comparison operator is used in a Boolean
1215 context (e.g., in the condition of an ``if`` statement), Python will call
1216 :func:`bool` on the value to determine if the result is true or false.
1217
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001218 There are no implied relationships among the comparison operators. The truth
1219 of ``x==y`` does not imply that ``x!=y`` is false. Accordingly, when
1220 defining :meth:`__eq__`, one should also define :meth:`__ne__` so that the
1221 operators will behave as expected. See the paragraph on :meth:`__hash__` for
1222 some important notes on creating :term:`hashable` objects which support
1223 custom comparison operations and are usable as dictionary keys.
Georg Brandl116aa622007-08-15 14:28:22 +00001224
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001225 There are no swapped-argument versions of these methods (to be used when the
1226 left argument does not support the operation but the right argument does);
1227 rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
Georg Brandl116aa622007-08-15 14:28:22 +00001228 :meth:`__le__` and :meth:`__ge__` are each other's reflection, and
1229 :meth:`__eq__` and :meth:`__ne__` are their own reflection.
1230
1231 Arguments to rich comparison methods are never coerced.
1232
Raymond Hettinger6c4b4b22009-03-12 00:25:29 +00001233 To automatically generate ordering operations from a single root operation,
Raymond Hettingerc50846a2010-04-05 18:56:31 +00001234 see :func:`functools.total_ordering`.
Georg Brandl116aa622007-08-15 14:28:22 +00001235
Georg Brandl116aa622007-08-15 14:28:22 +00001236.. method:: object.__hash__(self)
1237
1238 .. index::
1239 object: dictionary
1240 builtin: hash
1241
Benjamin Peterson6cadba72008-11-19 22:38:29 +00001242 Called by built-in function :func:`hash` and for operations on members of
1243 hashed collections including :class:`set`, :class:`frozenset`, and
1244 :class:`dict`. :meth:`__hash__` should return an integer. The only required
1245 property is that objects which compare equal have the same hash value; it is
1246 advised to somehow mix together (e.g. using exclusive or) the hash values for
1247 the components of the object that also play a part in comparison of objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001248
Georg Brandl05f5ab72008-09-24 09:11:47 +00001249 If a class does not define an :meth:`__eq__` method it should not define a
1250 :meth:`__hash__` operation either; if it defines :meth:`__eq__` but not
Benjamin Peterson6cadba72008-11-19 22:38:29 +00001251 :meth:`__hash__`, its instances will not be usable as items in hashable
1252 collections. If a class defines mutable objects and implements an
1253 :meth:`__eq__` method, it should not implement :meth:`__hash__`, since the
1254 implementation of hashable collections requires that a key's hash value is
1255 immutable (if the object's hash value changes, it will be in the wrong hash
1256 bucket).
1257
Georg Brandldb629672007-11-03 08:44:43 +00001258
Georg Brandl05f5ab72008-09-24 09:11:47 +00001259 User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods
Nick Coghlan73c96db2008-08-31 13:21:24 +00001260 by default; with them, all objects compare unequal (except with themselves)
1261 and ``x.__hash__()`` returns ``id(x)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001262
Nick Coghlan73c96db2008-08-31 13:21:24 +00001263 Classes which inherit a :meth:`__hash__` method from a parent class but
Georg Brandl05f5ab72008-09-24 09:11:47 +00001264 change the meaning of :meth:`__eq__` such that the hash value returned is no
1265 longer appropriate (e.g. by switching to a value-based concept of equality
1266 instead of the default identity based equality) can explicitly flag
1267 themselves as being unhashable by setting ``__hash__ = None`` in the class
1268 definition. Doing so means that not only will instances of the class raise an
1269 appropriate :exc:`TypeError` when a program attempts to retrieve their hash
1270 value, but they will also be correctly identified as unhashable when checking
1271 ``isinstance(obj, collections.Hashable)`` (unlike classes which define their
1272 own :meth:`__hash__` to explicitly raise :exc:`TypeError`).
Nick Coghlan73c96db2008-08-31 13:21:24 +00001273
Georg Brandlae2dbe22009-03-13 19:04:40 +00001274 If a class that overrides :meth:`__eq__` needs to retain the implementation
Georg Brandl05f5ab72008-09-24 09:11:47 +00001275 of :meth:`__hash__` from a parent class, the interpreter must be told this
1276 explicitly by setting ``__hash__ = <ParentClass>.__hash__``. Otherwise the
1277 inheritance of :meth:`__hash__` will be blocked, just as if :attr:`__hash__`
1278 had been explicitly set to :const:`None`.
1279
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001280 See also the :option:`-R` command-line option.
1281
Georg Brandl116aa622007-08-15 14:28:22 +00001282
1283.. method:: object.__bool__(self)
Georg Brandl1aeaadd2008-09-06 17:42:52 +00001284
Georg Brandl116aa622007-08-15 14:28:22 +00001285 .. index:: single: __len__() (mapping object method)
1286
Benjamin Petersonf07d0022009-03-21 17:31:58 +00001287 Called to implement truth value testing and the built-in operation
Amaury Forgeot d'Arc097cd072009-07-07 00:43:08 +00001288 ``bool()``; should return ``False`` or ``True``. When this method is not
1289 defined, :meth:`__len__` is called, if it is defined, and the object is
1290 considered true if its result is nonzero. If a class defines neither
1291 :meth:`__len__` nor :meth:`__bool__`, all its instances are considered
1292 true.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294
Georg Brandl116aa622007-08-15 14:28:22 +00001295.. _attribute-access:
1296
1297Customizing attribute access
1298----------------------------
1299
1300The following methods can be defined to customize the meaning of attribute
1301access (use of, assignment to, or deletion of ``x.name``) for class instances.
1302
Georg Brandl85eb8c12007-08-31 16:33:38 +00001303.. XXX explain how descriptors interfere here!
1304
Georg Brandl116aa622007-08-15 14:28:22 +00001305
1306.. method:: object.__getattr__(self, name)
1307
1308 Called when an attribute lookup has not found the attribute in the usual places
1309 (i.e. it is not an instance attribute nor is it found in the class tree for
1310 ``self``). ``name`` is the attribute name. This method should return the
1311 (computed) attribute value or raise an :exc:`AttributeError` exception.
1312
Georg Brandl116aa622007-08-15 14:28:22 +00001313 Note that if the attribute is found through the normal mechanism,
1314 :meth:`__getattr__` is not called. (This is an intentional asymmetry between
1315 :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00001316 reasons and because otherwise :meth:`__getattr__` would have no way to access
Georg Brandl116aa622007-08-15 14:28:22 +00001317 other attributes of the instance. Note that at least for instance variables,
1318 you can fake total control by not inserting any values in the instance attribute
1319 dictionary (but instead inserting them in another object). See the
Georg Brandl85eb8c12007-08-31 16:33:38 +00001320 :meth:`__getattribute__` method below for a way to actually get total control
1321 over attribute access.
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323
1324.. method:: object.__getattribute__(self, name)
1325
1326 Called unconditionally to implement attribute accesses for instances of the
1327 class. If the class also defines :meth:`__getattr__`, the latter will not be
1328 called unless :meth:`__getattribute__` either calls it explicitly or raises an
1329 :exc:`AttributeError`. This method should return the (computed) attribute value
1330 or raise an :exc:`AttributeError` exception. In order to avoid infinite
1331 recursion in this method, its implementation should always call the base class
1332 method with the same name to access any attributes it needs, for example,
1333 ``object.__getattribute__(self, name)``.
1334
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00001335 .. note::
1336
1337 This method may still be bypassed when looking up special methods as the
Georg Brandl22b34312009-07-26 14:54:51 +00001338 result of implicit invocation via language syntax or built-in functions.
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00001339 See :ref:`special-lookup`.
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341
Georg Brandl85eb8c12007-08-31 16:33:38 +00001342.. method:: object.__setattr__(self, name, value)
1343
1344 Called when an attribute assignment is attempted. This is called instead of
1345 the normal mechanism (i.e. store the value in the instance dictionary).
1346 *name* is the attribute name, *value* is the value to be assigned to it.
1347
1348 If :meth:`__setattr__` wants to assign to an instance attribute, it should
1349 call the base class method with the same name, for example,
1350 ``object.__setattr__(self, name, value)``.
1351
1352
1353.. method:: object.__delattr__(self, name)
1354
1355 Like :meth:`__setattr__` but for attribute deletion instead of assignment. This
1356 should only be implemented if ``del obj.name`` is meaningful for the object.
1357
1358
Benjamin Peterson1cef37c2008-07-02 14:44:54 +00001359.. method:: object.__dir__(self)
1360
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001361 Called when :func:`dir` is called on the object. A sequence must be
1362 returned. :func:`dir` converts the returned sequence to a list and sorts it.
Benjamin Peterson1cef37c2008-07-02 14:44:54 +00001363
1364
Georg Brandl116aa622007-08-15 14:28:22 +00001365.. _descriptors:
1366
1367Implementing Descriptors
1368^^^^^^^^^^^^^^^^^^^^^^^^
1369
1370The following methods only apply when an instance of the class containing the
Raymond Hettinger3b654be2011-03-22 16:27:02 -07001371method (a so-called *descriptor* class) appears in an *owner* class (the
1372descriptor must be in either the owner's class dictionary or in the class
1373dictionary for one of its parents). In the examples below, "the attribute"
1374refers to the attribute whose name is the key of the property in the owner
1375class' :attr:`__dict__`.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377
1378.. method:: object.__get__(self, instance, owner)
1379
1380 Called to get the attribute of the owner class (class attribute access) or of an
1381 instance of that class (instance attribute access). *owner* is always the owner
1382 class, while *instance* is the instance that the attribute was accessed through,
1383 or ``None`` when the attribute is accessed through the *owner*. This method
1384 should return the (computed) attribute value or raise an :exc:`AttributeError`
1385 exception.
1386
1387
1388.. method:: object.__set__(self, instance, value)
1389
1390 Called to set the attribute on an instance *instance* of the owner class to a
1391 new value, *value*.
1392
1393
1394.. method:: object.__delete__(self, instance)
1395
1396 Called to delete the attribute on an instance *instance* of the owner class.
1397
1398
1399.. _descriptor-invocation:
1400
1401Invoking Descriptors
1402^^^^^^^^^^^^^^^^^^^^
1403
1404In general, a descriptor is an object attribute with "binding behavior", one
1405whose attribute access has been overridden by methods in the descriptor
1406protocol: :meth:`__get__`, :meth:`__set__`, and :meth:`__delete__`. If any of
1407those methods are defined for an object, it is said to be a descriptor.
1408
1409The default behavior for attribute access is to get, set, or delete the
1410attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain
1411starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
1412continuing through the base classes of ``type(a)`` excluding metaclasses.
1413
1414However, if the looked-up value is an object defining one of the descriptor
1415methods, then Python may override the default behavior and invoke the descriptor
1416method instead. Where this occurs in the precedence chain depends on which
Georg Brandl23e8db52008-04-07 19:17:06 +00001417descriptor methods were defined and how they were called.
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419The starting point for descriptor invocation is a binding, ``a.x``. How the
1420arguments are assembled depends on ``a``:
1421
1422Direct Call
1423 The simplest and least common call is when user code directly invokes a
1424 descriptor method: ``x.__get__(a)``.
1425
1426Instance Binding
Georg Brandl85eb8c12007-08-31 16:33:38 +00001427 If binding to an object instance, ``a.x`` is transformed into the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001428 ``type(a).__dict__['x'].__get__(a, type(a))``.
1429
1430Class Binding
Georg Brandl85eb8c12007-08-31 16:33:38 +00001431 If binding to a class, ``A.x`` is transformed into the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001432 ``A.__dict__['x'].__get__(None, A)``.
1433
1434Super Binding
1435 If ``a`` is an instance of :class:`super`, then the binding ``super(B,
1436 obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A``
1437 immediately preceding ``B`` and then invokes the descriptor with the call:
Raymond Hettingerb199b222011-03-22 15:28:45 -07001438 ``A.__dict__['m'].__get__(obj, obj.__class__)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440For instance bindings, the precedence of descriptor invocation depends on the
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001441which descriptor methods are defined. A descriptor can define any combination
1442of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not
1443define :meth:`__get__`, then accessing the attribute will return the descriptor
1444object itself unless there is a value in the object's instance dictionary. If
1445the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data
1446descriptor; if it defines neither, it is a non-data descriptor. Normally, data
1447descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data
1448descriptors have just the :meth:`__get__` method. Data descriptors with
1449:meth:`__set__` and :meth:`__get__` defined always override a redefinition in an
Georg Brandl116aa622007-08-15 14:28:22 +00001450instance dictionary. In contrast, non-data descriptors can be overridden by
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00001451instances.
Georg Brandl116aa622007-08-15 14:28:22 +00001452
1453Python methods (including :func:`staticmethod` and :func:`classmethod`) are
1454implemented as non-data descriptors. Accordingly, instances can redefine and
1455override methods. This allows individual instances to acquire behaviors that
1456differ from other instances of the same class.
1457
1458The :func:`property` function is implemented as a data descriptor. Accordingly,
1459instances cannot override the behavior of a property.
1460
1461
1462.. _slots:
1463
1464__slots__
1465^^^^^^^^^
1466
Georg Brandl85eb8c12007-08-31 16:33:38 +00001467By default, instances of classes have a dictionary for attribute storage. This
1468wastes space for objects having very few instance variables. The space
1469consumption can become acute when creating large numbers of instances.
Georg Brandl116aa622007-08-15 14:28:22 +00001470
Georg Brandl85eb8c12007-08-31 16:33:38 +00001471The default can be overridden by defining *__slots__* in a class definition.
1472The *__slots__* declaration takes a sequence of instance variables and reserves
1473just enough space in each instance to hold a value for each variable. Space is
1474saved because *__dict__* is not created for each instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001475
1476
Georg Brandl85eb8c12007-08-31 16:33:38 +00001477.. data:: object.__slots__
Georg Brandl116aa622007-08-15 14:28:22 +00001478
Georg Brandl85eb8c12007-08-31 16:33:38 +00001479 This class variable can be assigned a string, iterable, or sequence of
Georg Brandl23e8db52008-04-07 19:17:06 +00001480 strings with variable names used by instances. If defined in a
Georg Brandl85eb8c12007-08-31 16:33:38 +00001481 class, *__slots__* reserves space for the declared variables and prevents the
1482 automatic creation of *__dict__* and *__weakref__* for each instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001483
Georg Brandl116aa622007-08-15 14:28:22 +00001484
1485Notes on using *__slots__*
Georg Brandl16174572007-09-01 12:38:06 +00001486""""""""""""""""""""""""""
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Georg Brandl3dbca812008-07-23 16:10:53 +00001488* When inheriting from a class without *__slots__*, the *__dict__* attribute of
1489 that class will always be accessible, so a *__slots__* definition in the
1490 subclass is meaningless.
1491
Georg Brandl116aa622007-08-15 14:28:22 +00001492* Without a *__dict__* variable, instances cannot be assigned new variables not
1493 listed in the *__slots__* definition. Attempts to assign to an unlisted
1494 variable name raises :exc:`AttributeError`. If dynamic assignment of new
Georg Brandl85eb8c12007-08-31 16:33:38 +00001495 variables is desired, then add ``'__dict__'`` to the sequence of strings in
1496 the *__slots__* declaration.
Georg Brandl116aa622007-08-15 14:28:22 +00001497
Georg Brandl116aa622007-08-15 14:28:22 +00001498* Without a *__weakref__* variable for each instance, classes defining
1499 *__slots__* do not support weak references to its instances. If weak reference
1500 support is needed, then add ``'__weakref__'`` to the sequence of strings in the
1501 *__slots__* declaration.
1502
Georg Brandl116aa622007-08-15 14:28:22 +00001503* *__slots__* are implemented at the class level by creating descriptors
1504 (:ref:`descriptors`) for each variable name. As a result, class attributes
1505 cannot be used to set default values for instance variables defined by
1506 *__slots__*; otherwise, the class attribute would overwrite the descriptor
1507 assignment.
1508
Georg Brandl495f7b52009-10-27 15:28:25 +00001509* The action of a *__slots__* declaration is limited to the class where it is
1510 defined. As a result, subclasses will have a *__dict__* unless they also define
1511 *__slots__* (which must only contain names of any *additional* slots).
1512
Georg Brandl116aa622007-08-15 14:28:22 +00001513* If a class defines a slot also defined in a base class, the instance variable
1514 defined by the base class slot is inaccessible (except by retrieving its
1515 descriptor directly from the base class). This renders the meaning of the
1516 program undefined. In the future, a check may be added to prevent this.
1517
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +00001518* Nonempty *__slots__* does not work for classes derived from "variable-length"
1519 built-in types such as :class:`int`, :class:`str` and :class:`tuple`.
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521* Any non-string iterable may be assigned to *__slots__*. Mappings may also be
1522 used; however, in the future, special meaning may be assigned to the values
1523 corresponding to each key.
1524
1525* *__class__* assignment works only if both classes have the same *__slots__*.
1526
Georg Brandl116aa622007-08-15 14:28:22 +00001527
1528.. _metaclasses:
1529
1530Customizing class creation
1531--------------------------
1532
Georg Brandl85eb8c12007-08-31 16:33:38 +00001533By default, classes are constructed using :func:`type`. A class definition is
1534read into a separate namespace and the value of class name is bound to the
1535result of ``type(name, bases, dict)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001536
Benjamin Petersone348d1a2008-10-19 21:29:05 +00001537When the class definition is read, if a callable ``metaclass`` keyword argument
1538is passed after the bases in the class definition, the callable given will be
1539called instead of :func:`type`. If other keyword arguments are passed, they
1540will also be passed to the metaclass. This allows classes or functions to be
1541written which monitor or alter the class creation process:
Georg Brandl116aa622007-08-15 14:28:22 +00001542
1543* Modifying the class dictionary prior to the class being created.
1544
1545* Returning an instance of another class -- essentially performing the role of a
1546 factory function.
1547
Christian Heimes790c8232008-01-07 21:14:23 +00001548These steps will have to be performed in the metaclass's :meth:`__new__` method
1549-- :meth:`type.__new__` can then be called from this method to create a class
1550with different properties. This example adds a new element to the class
1551dictionary before creating the class::
1552
1553 class metacls(type):
1554 def __new__(mcs, name, bases, dict):
1555 dict['foo'] = 'metacls was here'
1556 return type.__new__(mcs, name, bases, dict)
1557
1558You can of course also override other class methods (or add new methods); for
1559example defining a custom :meth:`__call__` method in the metaclass allows custom
1560behavior when the class is called, e.g. not always creating a new instance.
1561
Benjamin Petersone348d1a2008-10-19 21:29:05 +00001562If the metaclass has a :meth:`__prepare__` attribute (usually implemented as a
1563class or static method), it is called before the class body is evaluated with
1564the name of the class and a tuple of its bases for arguments. It should return
1565an object that supports the mapping interface that will be used to store the
1566namespace of the class. The default is a plain dictionary. This could be used,
1567for example, to keep track of the order that class attributes are declared in by
1568returning an ordered dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Georg Brandl116aa622007-08-15 14:28:22 +00001570The appropriate metaclass is determined by the following precedence rules:
1571
Georg Brandlf43713f2009-10-22 16:08:10 +00001572* If the ``metaclass`` keyword argument is passed with the bases, it is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
Benjamin Petersone348d1a2008-10-19 21:29:05 +00001574* Otherwise, if there is at least one base class, its metaclass is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001575
Georg Brandl85eb8c12007-08-31 16:33:38 +00001576* Otherwise, the default metaclass (:class:`type`) is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
1578The potential uses for metaclasses are boundless. Some ideas that have been
1579explored including logging, interface checking, automatic delegation, automatic
1580property creation, proxies, frameworks, and automatic resource
1581locking/synchronization.
1582
Raymond Hettinger15efcb62009-04-07 02:09:15 +00001583Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
1584to remember the order that class members were defined::
Raymond Hettinger958e3682009-04-07 02:08:23 +00001585
1586 class OrderedClass(type):
1587
1588 @classmethod
1589 def __prepare__(metacls, name, bases, **kwds):
1590 return collections.OrderedDict()
1591
1592 def __new__(cls, name, bases, classdict):
1593 result = type.__new__(cls, name, bases, dict(classdict))
1594 result.members = tuple(classdict)
1595 return result
1596
1597 class A(metaclass=OrderedClass):
1598 def one(self): pass
1599 def two(self): pass
1600 def three(self): pass
1601 def four(self): pass
1602
1603 >>> A.members
1604 ('__module__', 'one', 'two', 'three', 'four')
1605
Raymond Hettingerc4faeea2009-04-07 02:31:14 +00001606When the class definition for *A* gets executed, the process begins with
1607calling the metaclass's :meth:`__prepare__` method which returns an empty
Raymond Hettinger958e3682009-04-07 02:08:23 +00001608:class:`collections.OrderedDict`. That mapping records the methods and
1609attributes of *A* as they are defined within the body of the class statement.
Raymond Hettingerc4faeea2009-04-07 02:31:14 +00001610Once those definitions are executed, the ordered dictionary is fully populated
Hirokazu Yamamotoae9eb5c2009-04-26 03:34:06 +00001611and the metaclass's :meth:`__new__` method gets invoked. That method builds
Raymond Hettingerc4faeea2009-04-07 02:31:14 +00001612the new type and it saves the ordered dictionary keys in an attribute
Fred Drake11c49a52010-11-13 04:24:26 +00001613called ``members``.
Raymond Hettinger958e3682009-04-07 02:08:23 +00001614
Georg Brandl116aa622007-08-15 14:28:22 +00001615
Georg Brandl8569e582010-05-19 20:57:08 +00001616Customizing instance and subclass checks
1617----------------------------------------
1618
1619The following methods are used to override the default behavior of the
1620:func:`isinstance` and :func:`issubclass` built-in functions.
1621
1622In particular, the metaclass :class:`abc.ABCMeta` implements these methods in
1623order to allow the addition of Abstract Base Classes (ABCs) as "virtual base
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001624classes" to any class or type (including built-in types), including other
Georg Brandl8569e582010-05-19 20:57:08 +00001625ABCs.
1626
1627.. method:: class.__instancecheck__(self, instance)
1628
1629 Return true if *instance* should be considered a (direct or indirect)
1630 instance of *class*. If defined, called to implement ``isinstance(instance,
1631 class)``.
1632
1633
1634.. method:: class.__subclasscheck__(self, subclass)
1635
1636 Return true if *subclass* should be considered a (direct or indirect)
1637 subclass of *class*. If defined, called to implement ``issubclass(subclass,
1638 class)``.
1639
1640
1641Note that these methods are looked up on the type (metaclass) of a class. They
1642cannot be defined as class methods in the actual class. This is consistent with
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001643the lookup of special methods that are called on instances, only in this
Georg Brandl8569e582010-05-19 20:57:08 +00001644case the instance is itself a class.
1645
1646.. seealso::
1647
1648 :pep:`3119` - Introducing Abstract Base Classes
1649 Includes the specification for customizing :func:`isinstance` and
1650 :func:`issubclass` behavior through :meth:`__instancecheck__` and
1651 :meth:`__subclasscheck__`, with motivation for this functionality in the
1652 context of adding Abstract Base Classes (see the :mod:`abc` module) to the
1653 language.
1654
1655
Georg Brandl116aa622007-08-15 14:28:22 +00001656.. _callable-types:
1657
1658Emulating callable objects
1659--------------------------
1660
1661
1662.. method:: object.__call__(self[, args...])
1663
1664 .. index:: pair: call; instance
1665
1666 Called when the instance is "called" as a function; if this method is defined,
1667 ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``.
1668
1669
1670.. _sequence-types:
1671
1672Emulating container types
1673-------------------------
1674
1675The following methods can be defined to implement container objects. Containers
1676usually are sequences (such as lists or tuples) or mappings (like dictionaries),
1677but can represent other containers as well. The first set of methods is used
1678either to emulate a sequence or to emulate a mapping; the difference is that for
1679a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
1680N`` where *N* is the length of the sequence, or slice objects, which define a
Georg Brandlcb8ecb12007-09-04 06:35:14 +00001681range of items. It is also recommended that mappings provide the methods
Georg Brandlc7723722008-05-26 17:47:11 +00001682:meth:`keys`, :meth:`values`, :meth:`items`, :meth:`get`, :meth:`clear`,
1683:meth:`setdefault`, :meth:`pop`, :meth:`popitem`, :meth:`copy`, and
Georg Brandlcb8ecb12007-09-04 06:35:14 +00001684:meth:`update` behaving similar to those for Python's standard dictionary
Georg Brandlc7723722008-05-26 17:47:11 +00001685objects. The :mod:`collections` module provides a :class:`MutableMapping`
1686abstract base class to help create those methods from a base set of
1687:meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and :meth:`keys`.
1688Mutable sequences should provide methods :meth:`append`, :meth:`count`,
1689:meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, :meth:`remove`,
1690:meth:`reverse` and :meth:`sort`, like Python standard list objects. Finally,
1691sequence types should implement addition (meaning concatenation) and
1692multiplication (meaning repetition) by defining the methods :meth:`__add__`,
1693:meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`, :meth:`__rmul__` and
1694:meth:`__imul__` described below; they should not define other numerical
1695operators. It is recommended that both mappings and sequences implement the
1696:meth:`__contains__` method to allow efficient use of the ``in`` operator; for
1697mappings, ``in`` should search the mapping's keys; for sequences, it should
1698search through the values. It is further recommended that both mappings and
1699sequences implement the :meth:`__iter__` method to allow efficient iteration
1700through the container; for mappings, :meth:`__iter__` should be the same as
Fred Drake2e748782007-09-04 17:33:11 +00001701:meth:`keys`; for sequences, it should iterate through the values.
Georg Brandl116aa622007-08-15 14:28:22 +00001702
1703.. method:: object.__len__(self)
1704
1705 .. index::
1706 builtin: len
1707 single: __bool__() (object method)
1708
1709 Called to implement the built-in function :func:`len`. Should return the length
1710 of the object, an integer ``>=`` 0. Also, an object that doesn't define a
1711 :meth:`__bool__` method and whose :meth:`__len__` method returns zero is
1712 considered to be false in a Boolean context.
1713
1714
Georg Brandlcb8ecb12007-09-04 06:35:14 +00001715.. note::
1716
1717 Slicing is done exclusively with the following three methods. A call like ::
1718
1719 a[1:2] = b
1720
1721 is translated to ::
1722
1723 a[slice(1, 2, None)] = b
1724
1725 and so forth. Missing slice items are always filled in with ``None``.
1726
1727
Georg Brandl116aa622007-08-15 14:28:22 +00001728.. method:: object.__getitem__(self, key)
1729
1730 .. index:: object: slice
1731
1732 Called to implement evaluation of ``self[key]``. For sequence types, the
1733 accepted keys should be integers and slice objects. Note that the special
1734 interpretation of negative indexes (if the class wishes to emulate a sequence
1735 type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate
1736 type, :exc:`TypeError` may be raised; if of a value outside the set of indexes
1737 for the sequence (after any special interpretation of negative values),
1738 :exc:`IndexError` should be raised. For mapping types, if *key* is missing (not
1739 in the container), :exc:`KeyError` should be raised.
1740
1741 .. note::
1742
1743 :keyword:`for` loops expect that an :exc:`IndexError` will be raised for illegal
1744 indexes to allow proper detection of the end of the sequence.
1745
1746
1747.. method:: object.__setitem__(self, key, value)
1748
1749 Called to implement assignment to ``self[key]``. Same note as for
1750 :meth:`__getitem__`. This should only be implemented for mappings if the
1751 objects support changes to the values for keys, or if new keys can be added, or
1752 for sequences if elements can be replaced. The same exceptions should be raised
1753 for improper *key* values as for the :meth:`__getitem__` method.
1754
1755
1756.. method:: object.__delitem__(self, key)
1757
1758 Called to implement deletion of ``self[key]``. Same note as for
1759 :meth:`__getitem__`. This should only be implemented for mappings if the
1760 objects support removal of keys, or for sequences if elements can be removed
1761 from the sequence. The same exceptions should be raised for improper *key*
1762 values as for the :meth:`__getitem__` method.
1763
1764
1765.. method:: object.__iter__(self)
1766
1767 This method is called when an iterator is required for a container. This method
1768 should return a new iterator object that can iterate over all the objects in the
1769 container. For mappings, it should iterate over the keys of the container, and
Fred Drake2e748782007-09-04 17:33:11 +00001770 should also be made available as the method :meth:`keys`.
Georg Brandl116aa622007-08-15 14:28:22 +00001771
1772 Iterator objects also need to implement this method; they are required to return
1773 themselves. For more information on iterator objects, see :ref:`typeiter`.
1774
Christian Heimes7f044312008-01-06 17:05:40 +00001775
1776.. method:: object.__reversed__(self)
1777
Georg Brandl22b34312009-07-26 14:54:51 +00001778 Called (if present) by the :func:`reversed` built-in to implement
Christian Heimes7f044312008-01-06 17:05:40 +00001779 reverse iteration. It should return a new iterator object that iterates
1780 over all the objects in the container in reverse order.
1781
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001782 If the :meth:`__reversed__` method is not provided, the :func:`reversed`
Georg Brandl22b34312009-07-26 14:54:51 +00001783 built-in will fall back to using the sequence protocol (:meth:`__len__` and
Georg Brandl8a1e4c42009-05-25 21:13:36 +00001784 :meth:`__getitem__`). Objects that support the sequence protocol should
1785 only provide :meth:`__reversed__` if they can provide an implementation
1786 that is more efficient than the one provided by :func:`reversed`.
Christian Heimes7f044312008-01-06 17:05:40 +00001787
1788
Georg Brandl116aa622007-08-15 14:28:22 +00001789The membership test operators (:keyword:`in` and :keyword:`not in`) are normally
1790implemented as an iteration through a sequence. However, container objects can
1791supply the following special method with a more efficient implementation, which
1792also does not require the object be a sequence.
1793
Georg Brandl116aa622007-08-15 14:28:22 +00001794.. method:: object.__contains__(self, item)
1795
Georg Brandl495f7b52009-10-27 15:28:25 +00001796 Called to implement membership test operators. Should return true if *item*
1797 is in *self*, false otherwise. For mapping objects, this should consider the
1798 keys of the mapping rather than the values or the key-item pairs.
1799
1800 For objects that don't define :meth:`__contains__`, the membership test first
1801 tries iteration via :meth:`__iter__`, then the old sequence iteration
1802 protocol via :meth:`__getitem__`, see :ref:`this section in the language
1803 reference <membership-test-details>`.
Georg Brandl116aa622007-08-15 14:28:22 +00001804
1805
Georg Brandl116aa622007-08-15 14:28:22 +00001806.. _numeric-types:
1807
1808Emulating numeric types
1809-----------------------
1810
1811The following methods can be defined to emulate numeric objects. Methods
1812corresponding to operations that are not supported by the particular kind of
1813number implemented (e.g., bitwise operations for non-integral numbers) should be
1814left undefined.
1815
1816
1817.. method:: object.__add__(self, other)
1818 object.__sub__(self, other)
1819 object.__mul__(self, other)
Georg Brandlae55dc02008-09-06 17:43:49 +00001820 object.__truediv__(self, other)
Georg Brandl116aa622007-08-15 14:28:22 +00001821 object.__floordiv__(self, other)
1822 object.__mod__(self, other)
1823 object.__divmod__(self, other)
1824 object.__pow__(self, other[, modulo])
1825 object.__lshift__(self, other)
1826 object.__rshift__(self, other)
1827 object.__and__(self, other)
1828 object.__xor__(self, other)
1829 object.__or__(self, other)
1830
1831 .. index::
1832 builtin: divmod
1833 builtin: pow
1834 builtin: pow
1835
1836 These methods are called to implement the binary arithmetic operations (``+``,
Georg Brandlae55dc02008-09-06 17:43:49 +00001837 ``-``, ``*``, ``/``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``,
Georg Brandl116aa622007-08-15 14:28:22 +00001838 ``>>``, ``&``, ``^``, ``|``). For instance, to evaluate the expression
Brett Cannon3a954da2008-08-14 05:59:39 +00001839 ``x + y``, where *x* is an instance of a class that has an :meth:`__add__`
Georg Brandl116aa622007-08-15 14:28:22 +00001840 method, ``x.__add__(y)`` is called. The :meth:`__divmod__` method should be the
1841 equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be
Georg Brandlae55dc02008-09-06 17:43:49 +00001842 related to :meth:`__truediv__`. Note that :meth:`__pow__` should be defined
1843 to accept an optional third argument if the ternary version of the built-in
1844 :func:`pow` function is to be supported.
Georg Brandl116aa622007-08-15 14:28:22 +00001845
1846 If one of those methods does not support the operation with the supplied
1847 arguments, it should return ``NotImplemented``.
1848
1849
Georg Brandl116aa622007-08-15 14:28:22 +00001850.. method:: object.__radd__(self, other)
1851 object.__rsub__(self, other)
1852 object.__rmul__(self, other)
Georg Brandl116aa622007-08-15 14:28:22 +00001853 object.__rtruediv__(self, other)
1854 object.__rfloordiv__(self, other)
1855 object.__rmod__(self, other)
1856 object.__rdivmod__(self, other)
1857 object.__rpow__(self, other)
1858 object.__rlshift__(self, other)
1859 object.__rrshift__(self, other)
1860 object.__rand__(self, other)
1861 object.__rxor__(self, other)
1862 object.__ror__(self, other)
1863
1864 .. index::
1865 builtin: divmod
1866 builtin: pow
1867
1868 These methods are called to implement the binary arithmetic operations (``+``,
Georg Brandlae55dc02008-09-06 17:43:49 +00001869 ``-``, ``*``, ``/``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``,
1870 ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected (swapped) operands.
1871 These functions are only called if the left operand does not support the
1872 corresponding operation and the operands are of different types. [#]_ For
1873 instance, to evaluate the expression ``x - y``, where *y* is an instance of
1874 a class that has an :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if
1875 ``x.__sub__(y)`` returns *NotImplemented*.
Georg Brandl116aa622007-08-15 14:28:22 +00001876
1877 .. index:: builtin: pow
1878
1879 Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
1880 coercion rules would become too complicated).
1881
1882 .. note::
1883
1884 If the right operand's type is a subclass of the left operand's type and that
1885 subclass provides the reflected method for the operation, this method will be
1886 called before the left operand's non-reflected method. This behavior allows
1887 subclasses to override their ancestors' operations.
1888
1889
1890.. method:: object.__iadd__(self, other)
1891 object.__isub__(self, other)
1892 object.__imul__(self, other)
Georg Brandl116aa622007-08-15 14:28:22 +00001893 object.__itruediv__(self, other)
1894 object.__ifloordiv__(self, other)
1895 object.__imod__(self, other)
1896 object.__ipow__(self, other[, modulo])
1897 object.__ilshift__(self, other)
1898 object.__irshift__(self, other)
1899 object.__iand__(self, other)
1900 object.__ixor__(self, other)
1901 object.__ior__(self, other)
1902
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001903 These methods are called to implement the augmented arithmetic assignments
Georg Brandl116aa622007-08-15 14:28:22 +00001904 (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
1905 ``&=``, ``^=``, ``|=``). These methods should attempt to do the operation
1906 in-place (modifying *self*) and return the result (which could be, but does
1907 not have to be, *self*). If a specific method is not defined, the augmented
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001908 assignment falls back to the normal methods. For instance, to execute the
1909 statement ``x += y``, where *x* is an instance of a class that has an
Georg Brandl116aa622007-08-15 14:28:22 +00001910 :meth:`__iadd__` method, ``x.__iadd__(y)`` is called. If *x* is an instance
1911 of a class that does not define a :meth:`__iadd__` method, ``x.__add__(y)``
Brett Cannon3a954da2008-08-14 05:59:39 +00001912 and ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``.
Georg Brandl116aa622007-08-15 14:28:22 +00001913
1914
1915.. method:: object.__neg__(self)
1916 object.__pos__(self)
1917 object.__abs__(self)
1918 object.__invert__(self)
1919
1920 .. index:: builtin: abs
1921
1922 Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
1923 and ``~``).
1924
1925
1926.. method:: object.__complex__(self)
1927 object.__int__(self)
Georg Brandl116aa622007-08-15 14:28:22 +00001928 object.__float__(self)
Mark Summerfield9557f602008-07-01 14:42:30 +00001929 object.__round__(self, [,n])
Georg Brandl116aa622007-08-15 14:28:22 +00001930
1931 .. index::
1932 builtin: complex
1933 builtin: int
Georg Brandl116aa622007-08-15 14:28:22 +00001934 builtin: float
Mark Summerfield9557f602008-07-01 14:42:30 +00001935 builtin: round
Georg Brandl116aa622007-08-15 14:28:22 +00001936
Mark Summerfield9557f602008-07-01 14:42:30 +00001937 Called to implement the built-in functions :func:`complex`,
1938 :func:`int`, :func:`float` and :func:`round`. Should return a value
1939 of the appropriate type.
Georg Brandl116aa622007-08-15 14:28:22 +00001940
1941
1942.. method:: object.__index__(self)
1943
1944 Called to implement :func:`operator.index`. Also called whenever Python needs
1945 an integer object (such as in slicing, or in the built-in :func:`bin`,
Georg Brandl5c106642007-11-29 17:41:05 +00001946 :func:`hex` and :func:`oct` functions). Must return an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001947
Georg Brandl116aa622007-08-15 14:28:22 +00001948
1949.. _context-managers:
1950
1951With Statement Context Managers
1952-------------------------------
1953
Georg Brandl116aa622007-08-15 14:28:22 +00001954A :dfn:`context manager` is an object that defines the runtime context to be
1955established when executing a :keyword:`with` statement. The context manager
1956handles the entry into, and the exit from, the desired runtime context for the
1957execution of the block of code. Context managers are normally invoked using the
1958:keyword:`with` statement (described in section :ref:`with`), but can also be
1959used by directly invoking their methods.
1960
1961.. index::
1962 statement: with
1963 single: context manager
1964
1965Typical uses of context managers include saving and restoring various kinds of
1966global state, locking and unlocking resources, closing opened files, etc.
1967
1968For more information on context managers, see :ref:`typecontextmanager`.
1969
1970
1971.. method:: object.__enter__(self)
1972
1973 Enter the runtime context related to this object. The :keyword:`with` statement
1974 will bind this method's return value to the target(s) specified in the
1975 :keyword:`as` clause of the statement, if any.
1976
1977
1978.. method:: object.__exit__(self, exc_type, exc_value, traceback)
1979
1980 Exit the runtime context related to this object. The parameters describe the
1981 exception that caused the context to be exited. If the context was exited
1982 without an exception, all three arguments will be :const:`None`.
1983
1984 If an exception is supplied, and the method wishes to suppress the exception
1985 (i.e., prevent it from being propagated), it should return a true value.
1986 Otherwise, the exception will be processed normally upon exit from this method.
1987
1988 Note that :meth:`__exit__` methods should not reraise the passed-in exception;
1989 this is the caller's responsibility.
1990
1991
1992.. seealso::
1993
1994 :pep:`0343` - The "with" statement
1995 The specification, background, and examples for the Python :keyword:`with`
1996 statement.
1997
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00001998
1999.. _special-lookup:
2000
2001Special method lookup
2002---------------------
2003
2004For custom classes, implicit invocations of special methods are only guaranteed
2005to work correctly if defined on an object's type, not in the object's instance
2006dictionary. That behaviour is the reason why the following code raises an
2007exception::
2008
Éric Araujo28053fb2010-11-22 03:09:19 +00002009 >>> class C:
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002010 ... pass
2011 ...
2012 >>> c = C()
2013 >>> c.__len__ = lambda: 5
2014 >>> len(c)
2015 Traceback (most recent call last):
2016 File "<stdin>", line 1, in <module>
2017 TypeError: object of type 'C' has no len()
2018
2019The rationale behind this behaviour lies with a number of special methods such
2020as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects,
2021including type objects. If the implicit lookup of these methods used the
2022conventional lookup process, they would fail when invoked on the type object
2023itself::
2024
2025 >>> 1 .__hash__() == hash(1)
2026 True
2027 >>> int.__hash__() == hash(int)
2028 Traceback (most recent call last):
2029 File "<stdin>", line 1, in <module>
2030 TypeError: descriptor '__hash__' of 'int' object needs an argument
2031
2032Incorrectly attempting to invoke an unbound method of a class in this way is
2033sometimes referred to as 'metaclass confusion', and is avoided by bypassing
2034the instance when looking up special methods::
2035
2036 >>> type(1).__hash__(1) == hash(1)
2037 True
2038 >>> type(int).__hash__(int) == hash(int)
2039 True
2040
2041In addition to bypassing any instance attributes in the interest of
Georg Brandlaf265f42008-12-07 15:06:20 +00002042correctness, implicit special method lookup generally also bypasses the
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002043:meth:`__getattribute__` method even of the object's metaclass::
2044
2045 >>> class Meta(type):
2046 ... def __getattribute__(*args):
Benjamin Peterson64106fb2008-10-29 20:35:35 +00002047 ... print("Metaclass getattribute invoked")
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002048 ... return type.__getattribute__(*args)
2049 ...
Benjamin Petersone348d1a2008-10-19 21:29:05 +00002050 >>> class C(object, metaclass=Meta):
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002051 ... def __len__(self):
2052 ... return 10
2053 ... def __getattribute__(*args):
Benjamin Peterson64106fb2008-10-29 20:35:35 +00002054 ... print("Class getattribute invoked")
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002055 ... return object.__getattribute__(*args)
2056 ...
2057 >>> c = C()
2058 >>> c.__len__() # Explicit lookup via instance
2059 Class getattribute invoked
2060 10
2061 >>> type(c).__len__(c) # Explicit lookup via type
2062 Metaclass getattribute invoked
2063 10
2064 >>> len(c) # Implicit lookup
2065 10
2066
2067Bypassing the :meth:`__getattribute__` machinery in this fashion
2068provides significant scope for speed optimisations within the
2069interpreter, at the cost of some flexibility in the handling of
2070special methods (the special method *must* be set on the class
2071object itself in order to be consistently invoked by the interpreter).
2072
2073
Georg Brandl116aa622007-08-15 14:28:22 +00002074.. rubric:: Footnotes
2075
Nick Coghlan3a5d7e32008-08-31 12:40:14 +00002076.. [#] It *is* possible in some cases to change an object's type, under certain
2077 controlled conditions. It generally isn't a good idea though, since it can
2078 lead to some very strange behaviour if it is handled incorrectly.
2079
Georg Brandl116aa622007-08-15 14:28:22 +00002080.. [#] For operands of the same type, it is assumed that if the non-reflected method
2081 (such as :meth:`__add__`) fails the operation is not supported, which is why the
2082 reflected method is not called.