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