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