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