rest25/reference/datamodel.rst => rest262/reference/datamodel.rst
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
n59-are still reachable.  (Implementation note: the current implementation uses a
n59+are still reachable.  (Implementation note: CPython currently 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
n63-Python Library Reference (XXX reference: ../lib/module-gc.html) for information
n63+documentation of the :mod:`gc` module for information on controlling the
64-on controlling the collection of cyclic garbage.)
64+collection of cyclic garbage.  Other implementations act differently and CPython
65+may change.)
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
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
n153-Numbers
n154+:class:`numbers.Number`
154   .. 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
n165-   Integers
n166+   :class:`numbers.Integral`
166      .. 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
n178-         These represent numbers in the range -2147483648 through 2147483647. (The range
n179+         These represent numbers in the range -2147483648 through 2147483647.
179-         may be larger on machines with a larger natural word size, but not smaller.)
180+         (The range may be larger on machines with a larger natural word size,
180-         When the result of an operation would fall outside this range, the result is
181+         but not smaller.)  When the result of an operation would fall outside
181-         normally returned as a long integer (in some cases, the exception
182+         this range, the result is normally returned as a long integer (in some
182-         :exc:`OverflowError` is raised instead). For the purpose of shift and mask
183+         cases, the exception :exc:`OverflowError` is raised instead).  For the
183-         operations, integers are assumed to have a binary, 2's complement notation using
184+         purpose of shift and mask operations, integers are assumed to have a
184-         32 or more bits, and hiding no bits from the user (i.e., all 4294967296
185+         binary, 2's complement notation using 32 or more bits, and hiding no
186+         bits from the user (i.e., all 4294967296 different bit patterns
185-         different bit patterns correspond to different values).
187+         correspond to different values).
186
187      Long integers
188         .. index:: object: long integer
189
n190-         These represent numbers in an unlimited range, subject to available (virtual)
n192+         These represent numbers in an unlimited range, subject to available
191-         memory only.  For the purpose of shift and mask operations, a binary
193+         (virtual) memory only.  For the purpose of shift and mask operations, a
192-         representation is assumed, and negative numbers are represented in a variant of
194+         binary representation is assumed, and negative numbers are represented
193-         2's complement which gives the illusion of an infinite string of sign bits
195+         in a variant of 2's complement which gives the illusion of an infinite
194-         extending to the left.
196+         string of sign bits extending to the left.
195
196      Booleans
197         .. index::
198            object: Boolean
199            single: False
200            single: True
201
n202-         These represent the truth values False and True.  The two objects representing
n204+         These represent the truth values False and True.  The two objects
203-         the values False and True are the only Boolean objects. The Boolean type is a
205+         representing the values False and True are the only Boolean objects.
204-         subtype of plain integers, and Boolean values behave like the values 0 and 1,
206+         The Boolean type is a subtype of plain integers, and Boolean values
205-         respectively, in almost all contexts, the exception being that when converted to
207+         behave like the values 0 and 1, respectively, in almost all contexts,
208+         the exception being that when converted to a string, the strings
206-         a string, the strings ``"False"`` or ``"True"`` are returned, respectively.
209+         ``"False"`` or ``"True"`` are returned, respectively.
207
208      .. index:: pair: integer; representation
209
n210-      The rules for integer representation are intended to give the most meaningful
n213+      The rules for integer representation are intended to give the most
211-      interpretation of shift and mask operations involving negative integers and the
214+      meaningful interpretation of shift and mask operations involving negative
212-      least surprises when switching between the plain and long integer domains.  Any
215+      integers and the least surprises when switching between the plain and long
213-      operation except left shift, if it yields a result in the plain integer domain
216+      integer domains.  Any operation, if it yields a result in the plain
214-      without causing overflow, will yield the same result in the long integer domain
217+      integer domain, will yield the same result in the long integer domain or
215-      or when using mixed operands.
218+      when using mixed operands.  The switch between domains is transparent to
219+      the programmer.
216
n217-      .. % Integers
n221+   :class:`numbers.Real` (:class:`float`)
218- 
219-   Floating point numbers
220      .. index::
221         object: floating point
222         pair: floating point; number
223         pair: C; language
224         pair: Java; language
225
n226-      These represent machine-level double precision floating point numbers.   You are
n228+      These represent machine-level double precision floating point numbers. You are
227      at the mercy of the underlying machine architecture (and C or Java
228      implementation) for the accepted range and handling of overflow. Python does not
229      support single-precision floating point numbers; the savings in processor and
230      memory usage that are usually the reason for using these is dwarfed by the
231      overhead of using objects in Python, so there is no reason to complicate the
232      language with two kinds of floating point numbers.
233
n234-   Complex numbers
n236+   :class:`numbers.Complex`
235      .. index::
236         object: complex
237         pair: complex; number
238
239      These represent complex numbers as a pair of machine-level double precision
240      floating point numbers.  The same caveats apply as for floating point numbers.
241      The real and imaginary parts of a complex number ``z`` can be retrieved through
242      the read-only attributes ``z.real`` and ``z.imag``.
n243- 
244-   .. % Numbers
245
246Sequences
247   .. index::
248      builtin: len
249      object: sequence
250      single: index operation
251      single: item selection
252      single: subscription
253
n254-   These represent finite ordered sets indexed by non-negative numbers. The built-
n254+   These represent finite ordered sets indexed by non-negative numbers. The
255-   in function :func:`len` returns the number of items of a sequence. When the
255+   built-in function :func:`len` returns the number of items of a sequence. When
256-   length of a sequence is *n*, the index set contains the numbers 0, 1, ...,
256+   the length of a sequence is *n*, the index set contains the numbers 0, 1,
257-   *n*-1.  Item *i* of sequence *a* is selected by ``a[i]``.
257+   ..., *n*-1.  Item *i* of sequence *a* is selected by ``a[i]``.
258
259   .. index:: single: slicing
260
261   Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such
262   that *i* ``<=`` *k* ``<`` *j*.  When used as an expression, a slice is a
263   sequence of the same type.  This implies that the index set is renumbered so
264   that it starts at 0.
265
341            pair: empty; tuple
342
343         The items of a tuple are arbitrary Python objects. Tuples of two or more items
344         are formed by comma-separated lists of expressions.  A tuple of one item (a
345         'singleton') can be formed by affixing a comma to an expression (an expression
346         by itself does not create a tuple, since parentheses must be usable for grouping
347         of expressions).  An empty tuple can be formed by an empty pair of parentheses.
348
n349-      .. % Immutable sequences
350- 
351   Mutable sequences
352      .. index::
353         object: mutable sequence
354         object: mutable
355         pair: assignment; statement
356         single: delete
357         statement: del
358         single: subscription
371         comma-separated list of expressions in square brackets. (Note that there are no
372         special cases needed to form lists of length 0 or 1.)
373
374      .. index:: module: array
375
376      The extension module :mod:`array` provides an additional example of a mutable
377      sequence type.
378
n379-      .. % Mutable sequences
n377+Set types
378+   .. index::
379+      builtin: len
380+      object: set type
380
n381-   .. % Sequences
n382+   These represent unordered, finite sets of unique, immutable objects. As such,
383+   they cannot be indexed by any subscript. However, they can be iterated over, and
384+   the built-in function :func:`len` returns the number of items in a set. Common
385+   uses for sets are fast membership testing, removing duplicates from a sequence,
386+   and computing mathematical operations such as intersection, union, difference,
387+   and symmetric difference.
388+ 
389+   For set elements, the same immutability rules apply as for dictionary keys. Note
390+   that numeric types obey the normal rules for numeric comparison: if two numbers
391+   compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a
392+   set.
393+ 
394+   There are currently two intrinsic set types:
395+ 
396+   Sets
397+      .. index:: object: set
398+ 
399+      These represent a mutable set. They are created by the built-in :func:`set`
400+      constructor and can be modified afterwards by several methods, such as
401+      :meth:`add`.
402+ 
403+   Frozen sets
404+      .. index:: object: frozenset
405+ 
406+      These represent an immutable set.  They are created by the built-in
407+      :func:`frozenset` constructor.  As a frozenset is immutable and
408+      :term:`hashable`, it can be used again as an element of another set, or as
409+      a dictionary key.
382
383Mappings
384   .. index::
385      builtin: len
386      single: subscription
387      object: mapping
388
389   These represent finite sets of objects indexed by arbitrary index sets. The
402      dictionaries or other mutable types that are compared by value rather than by
403      object identity, the reason being that the efficient implementation of
404      dictionaries requires a key's hash value to remain constant. Numeric types used
405      for keys obey the normal rules for numeric comparison: if two numbers compare
406      equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index
407      the same dictionary entry.
408
409      Dictionaries are mutable; they can be created by the ``{...}`` notation (see
n410-      section :ref:`dict`, "Dictionary Displays").
n438+      section :ref:`dict`).
411
412      .. index::
413         module: dbm
414         module: gdbm
415         module: bsddb
416
417      The extension modules :mod:`dbm`, :mod:`gdbm`, and :mod:`bsddb` provide
418      additional examples of mapping types.
n419- 
420-   .. % Mapping types
421
422Callable types
423   .. index::
424      object: callable
425      pair: function; call
426      single: invocation
427      pair: function; argument
428
429   These are the types to which the function call operation (see section
n430-   :ref:`calls`, "Calls") can be applied:
n456+   :ref:`calls`) can be applied:
431
432   User-defined functions
433      .. index::
434         pair: user-defined; function
435         object: function
436         object: user-defined function
437
n438-      A user-defined function object is created by a function definition (see section
n464+      A user-defined function object is created by a function definition (see
439-      :ref:`function`, "Function definitions").  It should be called with an argument
465+      section :ref:`function`).  It should be called with an argument list
440-      list containing the same number of items as the function's formal parameter
466+      containing the same number of items as the function's formal parameter
441      list.
442
443      Special attributes:
444
445      +-----------------------+-------------------------------+-----------+
446      | Attribute             | Meaning                       |           |
447      +=======================+===============================+===========+
448      | :attr:`func_doc`      | The function's documentation  | Writable  |
528      unbound methods; :attr:`__doc__` is the method's documentation (same as
529      ``im_func.__doc__``); :attr:`__name__` is the method name (same as
530      ``im_func.__name__``); :attr:`__module__` is the name of the module the method
531      was defined in, or ``None`` if unavailable.
532
533      .. versionchanged:: 2.2
534         :attr:`im_self` used to refer to the class that defined the method.
535
n562+      .. versionchanged:: 2.6
563+         For 3.0 forward-compatibility, :attr:`im_func` is also available as
564+         :attr:`__func__`, and :attr:`im_self` as :attr:`__self__`.
565+ 
536      .. index::
537         single: __doc__ (method attribute)
538         single: __name__ (method attribute)
539         single: __module__ (method attribute)
540         single: im_func (method attribute)
541         single: im_self (method attribute)
542
543      Methods also support accessing (but not setting) the arbitrary function
552      the original method object is used as it is.
553
554      .. index::
555         single: im_class (method attribute)
556         single: im_func (method attribute)
557         single: im_self (method attribute)
558
559      When a user-defined method object is created by retrieving a user-defined
n560-      function object from a class, its :attr:`im_self` attribute is ``None`` and the
n590+      function object from a class, its :attr:`im_self` attribute is ``None``
561-      method object is said to be unbound. When one is created by retrieving a user-
591+      and the method object is said to be unbound. When one is created by
562-      defined function object from a class via one of its instances, its
592+      retrieving a user-defined function object from a class via one of its
563-      :attr:`im_self` attribute is the instance, and the method object is said to be
593+      instances, its :attr:`im_self` attribute is the instance, and the method
564-      bound. In either case, the new method's :attr:`im_class` attribute is the class
594+      object is said to be bound. In either case, the new method's
565-      from which the retrieval takes place, and its :attr:`im_func` attribute is the
595+      :attr:`im_class` attribute is the class from which the retrieval takes
566-      original function object.
596+      place, and its :attr:`im_func` attribute is the original function object.
567
568      .. index:: single: im_func (method attribute)
569
570      When a user-defined method object is created by retrieving another method object
571      from a class or instance, the behaviour is the same as for a function object,
572      except that the :attr:`im_func` attribute of the new instance is not the
573      original method object but its :attr:`im_func` attribute.
574
609      attribute of the class.
610
611   Generator functions
612      .. index::
613         single: generator; function
614         single: generator; iterator
615
616      A function or method which uses the :keyword:`yield` statement (see section
n617-      :ref:`yield`, "The :keyword:`yield` statement") is called a :dfn:`generator
n647+      :ref:`yield`) is called a :dfn:`generator
618      function`.  Such a function, when called, always returns an iterator object
619      which can be used to execute the body of the function:  calling the iterator's
620      :meth:`next` method will cause the function to execute until it provides a value
621      using the :keyword:`yield` statement.  When the function executes a
622      :keyword:`return` statement or falls off the end, a :exc:`StopIteration`
623      exception is raised and the iterator will have reached the end of the set of
624      values to be returned.
625
626   Built-in functions
627      .. index::
628         object: built-in function
629         object: function
630         pair: C; language
631
n632-      A built-in function object is a wrapper around a C function.  Examples of built-
n662+      A built-in function object is a wrapper around a C function.  Examples of
633-      in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a standard
663+      built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
634-      built-in module). The number and type of the arguments are determined by the C
664+      standard built-in module). The number and type of the arguments are
635-      function. Special read-only attributes: :attr:`__doc__` is the function's
665+      determined by the C function. Special read-only attributes:
636-      documentation string, or ``None`` if unavailable; :attr:`__name__` is the
666+      :attr:`__doc__` is the function's documentation string, or ``None`` if
637-      function's name; :attr:`__self__` is set to ``None`` (but see the next item);
667+      unavailable; :attr:`__name__` is the function's name; :attr:`__self__` is
638-      :attr:`__module__` is the name of the module the function was defined in or
668+      set to ``None`` (but see the next item); :attr:`__module__` is the name of
639-      ``None`` if unavailable.
669+      the module the function was defined in or ``None`` if unavailable.
640
641   Built-in methods
642      .. index::
643         object: built-in method
644         object: method
645         pair: built-in; method
646
647      This is really a different disguise of a built-in function, this time containing
677      ``x.__call__(arguments)``.
678
679Modules
680   .. index::
681      statement: import
682      object: module
683
684   Modules are imported by the :keyword:`import` statement (see section
n685-   :ref:`import`, "The :keyword:`import` statement"). A module object has a
n715+   :ref:`import`). A module object has a
686   namespace implemented by a dictionary object (this is the dictionary referenced
687   by the func_globals attribute of functions defined in the module).  Attribute
688   references are translated to lookups in this dictionary, e.g., ``m.x`` is
689   equivalent to ``m.__dict__["x"]``. A module object does not contain the code
690   object used to initialize the module (since it isn't needed once the
691   initialization is done).
n692- 
693-   .. % 
694
695   Attribute assignment updates the module's namespace dictionary, e.g., ``m.x =
696   1`` is equivalent to ``m.__dict__["x"] = 1``.
697
698   .. index:: single: __dict__ (module attribute)
699
700   Special read-only attribute: :attr:`__dict__` is the module's namespace as a
701   dictionary object.
710   :attr:`__doc__` is the module's documentation string, or ``None`` if
711   unavailable; :attr:`__file__` is the pathname of the file from which the module
712   was loaded, if it was loaded from a file. The :attr:`__file__` attribute is not
713   present for C modules that are statically linked into the interpreter; for
714   extension modules loaded dynamically from a shared library, it is the pathname
715   of the shared library file.
716
717Classes
n718-   Class objects are created by class definitions (see section :ref:`class`, "Class
n746+   Both class types (new-style classes) and class objects (old-style/classic
747+   classes) are typically created by class definitions (see section
719-   definitions"). A class has a namespace implemented by a dictionary object. Class
748+   :ref:`class`).  A class has a namespace implemented by a dictionary object.
720-   attribute references are translated to lookups in this dictionary, e.g., ``C.x``
749+   Class attribute references are translated to lookups in this dictionary, e.g.,
721-   is translated to ``C.__dict__["x"]``. When the attribute name is not found
750+   ``C.x`` is translated to ``C.__dict__["x"]`` (although for new-style classes
722-   there, the attribute search continues in the base classes.  The search is depth-
751+   in particular there are a number of hooks which allow for other means of
752+   locating attributes). When the attribute name is not found there, the
753+   attribute search continues in the base classes.  For old-style classes, the
723-   first, left-to-right in the order of occurrence in the base class list.
754+   search is depth-first, left-to-right in the order of occurrence in the base
755+   class list. New-style classes use the more complex C3 method resolution
756+   order which behaves correctly even in the presence of 'diamond'
757+   inheritance structures where there are multiple inheritance paths
758+   leading back to a common ancestor. Additional details on the C3 MRO used by
759+   new-style classes can be found in the documentation accompanying the
760+   2.3 release at http://www.python.org/download/releases/2.3/mro/.
761+ 
762+   .. XXX: Could we add that MRO doc as an appendix to the language ref?
724
725   .. index::
726      object: class
727      object: class instance
728      object: instance
729      pair: class object; call
730      single: container
731      object: dictionary
732      pair: class; attribute
733
n734-   When a class attribute reference (for class :class:`C`, say) would yield a user-
n773+   When a class attribute reference (for class :class:`C`, say) would yield a
735-   defined function object or an unbound user-defined method object whose
774+   user-defined function object or an unbound user-defined method object whose
736   associated class is either :class:`C` or one of its base classes, it is
737   transformed into an unbound user-defined method object whose :attr:`im_class`
738   attribute is :class:`C`. When it would yield a class method object, it is
n739-   transformed into a bound user-defined method object whose :attr:`im_class` and
n778+   transformed into a bound user-defined method object whose :attr:`im_class`
740-   :attr:`im_self` attributes are both :class:`C`.  When it would yield a static
779+   and :attr:`im_self` attributes are both :class:`C`.  When it would yield a
741-   method object, it is transformed into the object wrapped by the static method
780+   static method object, it is transformed into the object wrapped by the static
742-   object. See section :ref:`descriptors` for another way in which attributes
781+   method object. See section :ref:`descriptors` for another way in which
743-   retrieved from a class may differ from those actually contained in its
782+   attributes retrieved from a class may differ from those actually contained in
744-   :attr:`__dict__`.
783+   its :attr:`__dict__` (note that only new-style classes support descriptors).
745
746   .. index:: triple: class; attribute; assignment
747
748   Class attribute assignments update the class's dictionary, never the dictionary
749   of a base class.
750
751   .. index:: pair: class object; call
752
798   dictionary directly.
799
800   .. index::
801      object: numeric
802      object: sequence
803      object: mapping
804
805   Class instances can pretend to be numbers, sequences, or mappings if they have
n806-   methods with certain special names.  See section :ref:`specialnames`, "Special
n845+   methods with certain special names.  See section :ref:`specialnames`.
807-   method names."
808
809   .. index::
810      single: __dict__ (instance attribute)
811      single: __class__ (instance attribute)
812
813   Special attributes: :attr:`__dict__` is the attribute dictionary;
814   :attr:`__class__` is the instance's class.
815
823      single: sys.stdout
824      single: sys.stderr
825      single: stdio
826      single: stdin (in module sys)
827      single: stdout (in module sys)
828      single: stderr (in module sys)
829
830   A file object represents an open file.  File objects are created by the
n831-   :func:`open` built-in function, and also by :func:`os.popen`, :func:`os.fdopen`,
n869+   :func:`open` built-in function, and also by :func:`os.popen`,
832-   and the :meth:`makefile` method of socket objects (and perhaps by other
870+   :func:`os.fdopen`, and the :meth:`makefile` method of socket objects (and
833-   functions or methods provided by extension modules).  The objects ``sys.stdin``,
871+   perhaps by other functions or methods provided by extension modules).  The
834-   ``sys.stdout`` and ``sys.stderr`` are initialized to file objects corresponding
872+   objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are initialized to
835-   to the interpreter's standard input, output and error streams.  See the Python
873+   file objects corresponding to the interpreter's standard input, output and
836-   Library Reference (XXX reference: ../lib/lib.html) for complete documentation of
874+   error streams.  See :ref:`bltin-file-objects` for complete documentation of
837   file objects.
838
839Internal types
840   .. index::
841      single: internal type
842      single: types, internal
843
844   A few types used internally by the interpreter are exposed to the user. Their
845   definitions may change with future versions of the interpreter, but they are
846   mentioned here for completeness.
847
848   Code objects
849      .. index::
850         single: bytecode
851         object: code
852
n853-      Code objects represent *byte-compiled* executable Python code, or  *bytecode*.
n891+      Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
854      The difference between a code object and a function object is that the function
855      object contains an explicit reference to the function's globals (the module in
n856-      which it was defined), while a code object contains no context;  also the
n894+      which it was defined), while a code object contains no context; also the default
857-      default argument values are stored in the function object, not in the code
895+      argument values are stored in the function object, not in the code object
858-      object (because they represent values calculated at run-time).  Unlike function
896+      (because they represent values calculated at run-time).  Unlike function
859      objects, code objects are immutable and contain no references (directly or
860      indirectly) to mutable objects.
861
862      Special read-only attributes: :attr:`co_name` gives the function name;
863      :attr:`co_argcount` is the number of positional arguments (including arguments
864      with default values); :attr:`co_nlocals` is the number of local variables used
865      by the function (including arguments); :attr:`co_varnames` is a tuple containing
866      the names of the local variables (starting with the argument names);
867      :attr:`co_cellvars` is a tuple containing the names of local variables that are
868      referenced by nested functions; :attr:`co_freevars` is a tuple containing the
869      names of free variables; :attr:`co_code` is a string representing the sequence
870      of bytecode instructions; :attr:`co_consts` is a tuple containing the literals
871      used by the bytecode; :attr:`co_names` is a tuple containing the names used by
872      the bytecode; :attr:`co_filename` is the filename from which the code was
873      compiled; :attr:`co_firstlineno` is the first line number of the function;
n874-      :attr:`co_lnotab` is a string encoding the mapping from byte code offsets to
n912+      :attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to
875      line numbers (for details see the source code of the interpreter);
876      :attr:`co_stacksize` is the required stack size (including local variables);
877      :attr:`co_flags` is an integer encoding a number of flags for the interpreter.
878
879      .. index::
880         single: co_argcount (code object attribute)
881         single: co_code (code object attribute)
882         single: co_consts (code object attribute)
949      :attr:`f_exc_type`, :attr:`f_exc_value`, :attr:`f_exc_traceback` represent the
950      last exception raised in the parent frame provided another exception was ever
951      raised in the current frame (in all other cases they are None); :attr:`f_lineno`
952      is the current line number of the frame --- writing to this from within a trace
953      function jumps to the given line (only for the bottom-most frame).  A debugger
954      can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
955
956   Traceback objects
n957-      .. _traceback:
958- 
959      .. index::
960         object: traceback
961         pair: stack; trace
962         pair: exception; handler
963         pair: execution; stack
964         single: exc_info (in module sys)
965         single: exc_traceback (in module sys)
966         single: last_traceback (in module sys)
968         single: sys.exc_traceback
969         single: sys.last_traceback
970
971      Traceback objects represent a stack trace of an exception.  A traceback object
972      is created when an exception occurs.  When the search for an exception handler
973      unwinds the execution stack, at each unwound level a traceback object is
974      inserted in front of the current traceback.  When an exception handler is
975      entered, the stack trace is made available to the program. (See section
n976-      :ref:`try`, "The ``try`` statement.") It is accessible as ``sys.exc_traceback``,
n1012+      :ref:`try`.) It is accessible as ``sys.exc_traceback``,
977      and also as the third item of the tuple returned by ``sys.exc_info()``.  The
978      latter is the preferred interface, since it works correctly when the program is
979      using multiple threads. When the program contains no suitable handler, the stack
980      trace is written (nicely formatted) to the standard error stream; if the
981      interpreter is interactive, it is also made available to the user as
982      ``sys.last_traceback``.
983
984      .. index::
1040
1041   Class method objects
1042      A class method object, like a static method object, is a wrapper around another
1043      object that alters the way in which that object is retrieved from classes and
1044      class instances. The behaviour of class method objects upon such retrieval is
1045      described above, under "User-defined methods". Class method objects are created
1046      by the built-in :func:`classmethod` constructor.
1047
n1048-   .. % Internal types
1049
n1050-.. % Types
n1085+.. _newstyle:
1051-.. % =========================================================================
1052- 
1053
1054New-style and classic classes
1055=============================
1056
n1057-Classes and instances come in two flavors: old-style or classic, and new-style.
n1090+Classes and instances come in two flavors: old-style (or classic) and new-style.
1058
1059Up to Python 2.1, old-style classes were the only flavour available to the user.
1060The concept of (old-style) class is unrelated to the concept of type: if *x* is
1061an instance of an old-style class, then ``x.__class__`` designates the class of
1062*x*, but ``type(x)`` is always ``<type 'instance'>``.  This reflects the fact
1063that all old-style instances, independently of their class, are implemented with
1064a single built-in type, called ``instance``.
1065
1066New-style classes were introduced in Python 2.2 to unify classes and types.  A
n1067-new-style class neither more nor less than a user-defined type.  If *x* is an
n1100+new-style class is neither more nor less than a user-defined type.  If *x* is an
1068-instance of a new-style class, then ``type(x)`` is the same as ``x.__class__``.
1101+instance of a new-style class, then ``type(x)`` is typically the same as
1102+``x.__class__`` (although this is not guaranteed - a new-style class instance is
1103+permitted to override the value returned for ``x.__class__``).
1069
1070The major motivation for introducing new-style classes is to provide a unified
n1071-object model with a full meta-model.  It also has a number of immediate
n1106+object model with a full meta-model.  It also has a number of practical
1072benefits, like the ability to subclass most built-in types, or the introduction
1073of "descriptors", which enable computed properties.
1074
1075For compatibility reasons, classes are still old-style by default.  New-style
1076classes are created by specifying another new-style class (i.e. a type) as a
1077parent class, or the "top-level type" :class:`object` if no other parent is
1078needed.  The behaviour of new-style classes differs from that of old-style
1079classes in a number of important details in addition to what :func:`type`
1080returns.  Some of these changes are fundamental to the new object model, like
1081the way special methods are invoked.  Others are "fixes" that could not be
1082implemented before for compatibility concerns, like the method resolution order
1083in case of multiple inheritance.
1084
n1085-This manual is not up-to-date with respect to new-style classes.  For now,
n1120+While this manual aims to provide comprehensive coverage of Python's class
1086-please see `<http://www.python.org/doc/newstyle.html>`_ for more information.
1121+mechanics, it may still be lacking in some areas when it comes to its coverage
1122+of new-style classes. Please see http://www.python.org/doc/newstyle/ for
1123+sources of additional information.
1087
1088.. index::
n1126+   single: class; new-style
1089-   single: class
1127+   single: class; classic
1090-   single: class
1128+   single: class; old-style
1091-   single: class
1092
n1093-The plan is to eventually drop old-style classes, leaving only the semantics of
n1130+Old-style classes are removed in Python 3.0, leaving only the semantics of
1094-new-style classes.  This change will probably only be feasible in Python 3.0.
1131+new-style classes.
1095-new-style classic old-style
1096- 
1097-.. % =========================================================================
1098
1099
1100.. _specialnames:
1101
1102Special method names
1103====================
1104
1105.. index::
1106   pair: operator; overloading
1107   single: __getitem__() (mapping object method)
1108
1109A class can implement certain operations that are invoked by special syntax
1110(such as arithmetic operations or subscripting and slicing) by defining methods
1111with special names. This is Python's approach to :dfn:`operator overloading`,
1112allowing classes to define their own behavior with respect to language
1113operators.  For instance, if a class defines a method named :meth:`__getitem__`,
n1114-and ``x`` is an instance of this class, then ``x[i]`` is equivalent [#]_ to
n1148+and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
1115-``x.__getitem__(i)``.  Except where mentioned, attempts to execute an operation
1149+to ``x.__getitem__(i)`` for old-style classes and ``type(x).__getitem__(x, i)``
1150+for new-style classes.  Except where mentioned, attempts to execute an
1116-raise an exception when no appropriate method is defined.
1151+operation raise an exception when no appropriate method is defined (typically
1152+:exc:`AttributeError` or :exc:`TypeError`).
1117
1118When implementing a class that emulates any built-in type, it is important that
1119the emulation only be implemented to the degree that it makes sense for the
1120object being modelled.  For example, some sequences may work well with retrieval
1121of individual elements, but extracting a slice may not make sense.  (One example
1122of this is the :class:`NodeList` interface in the W3C's Document Object Model.)
1123
1124
1125.. _customization:
1126
1127Basic customization
1128-------------------
1129
n1130- 
1131.. method:: object.__new__(cls[, ...])
n1167+ 
1168+   .. index:: pair: subclassing; immutable types
1132
1133   Called to create a new instance of class *cls*.  :meth:`__new__` is a static
1134   method (special-cased so you need not declare it as such) that takes the class
1135   of which an instance was requested as its first argument.  The remaining
1136   arguments are those passed to the object constructor expression (the call to the
1137   class).  The return value of :meth:`__new__` should be the new object instance
1138   (usually an instance of *cls*).
1139
1146   :meth:`__init__` method will be invoked like ``__init__(self[, ...])``, where
1147   *self* is the new instance and the remaining arguments are the same as were
1148   passed to :meth:`__new__`.
1149
1150   If :meth:`__new__` does not return an instance of *cls*, then the new instance's
1151   :meth:`__init__` method will not be invoked.
1152
1153   :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
n1154-   int, str, or tuple) to customize instance creation.
n1191+   int, str, or tuple) to customize instance creation.  It is also commonly
1192+   overridden in custom metaclasses in order to customize class creation.
1155
1156
1157.. method:: object.__init__(self[, ...])
1158
1159   .. index:: pair: class; constructor
1160
1161   Called when the instance is created.  The arguments are those passed to the
1162   class constructor expression.  If a base class has an :meth:`__init__` method,
1180   (though not recommended!) for the :meth:`__del__` method to postpone destruction
1181   of the instance by creating a new reference to it.  It may then be called at a
1182   later time when this new reference is deleted.  It is not guaranteed that
1183   :meth:`__del__` methods are called for objects that still exist when the
1184   interpreter exits.
1185
1186   .. note::
1187
n1188-      ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements the
n1226+      ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
1189-      reference count for ``x`` by one, and the latter is only called when ``x``'s
1227+      the reference count for ``x`` by one, and the latter is only called when
1190-      reference count reaches zero.  Some common situations that may prevent the
1228+      ``x``'s reference count reaches zero.  Some common situations that may
1191-      reference count of an object from going to zero include: circular references
1229+      prevent the reference count of an object from going to zero include:
1192-      between objects (e.g., a doubly-linked list or a tree data structure with parent
1230+      circular references between objects (e.g., a doubly-linked list or a tree
1193-      and child pointers); a reference to the object on the stack frame of a function
1231+      data structure with parent and child pointers); a reference to the object
1194-      that caught an exception (the traceback stored in ``sys.exc_traceback`` keeps
1232+      on the stack frame of a function that caught an exception (the traceback
1195-      the stack frame alive); or a reference to the object on the stack frame that
1233+      stored in ``sys.exc_traceback`` keeps the stack frame alive); or a
1234+      reference to the object on the stack frame that raised an unhandled
1196-      raised an unhandled exception in interactive mode (the traceback stored in
1235+      exception in interactive mode (the traceback stored in
1197-      ``sys.last_traceback`` keeps the stack frame alive).  The first situation can
1236+      ``sys.last_traceback`` keeps the stack frame alive).  The first situation
1198-      only be remedied by explicitly breaking the cycles; the latter two situations
1237+      can only be remedied by explicitly breaking the cycles; the latter two
1199-      can be resolved by storing ``None`` in ``sys.exc_traceback`` or
1238+      situations can be resolved by storing ``None`` in ``sys.exc_traceback`` or
1200-      ``sys.last_traceback``.  Circular references which are garbage are detected when
1239+      ``sys.last_traceback``.  Circular references which are garbage are
1201-      the option cycle detector is enabled (it's on by default), but can only be
1240+      detected when the option cycle detector is enabled (it's on by default),
1202-      cleaned up if there are no Python-level :meth:`__del__` methods involved. Refer
1241+      but can only be cleaned up if there are no Python-level :meth:`__del__`
1203-      to the documentation for the :mod:`gc` module (XXX reference: ../lib/module-
1242+      methods involved. Refer to the documentation for the :mod:`gc` module for
1204-      gc.html) for more information about how :meth:`__del__` methods are handled by
1243+      more information about how :meth:`__del__` methods are handled by the
1205-      the cycle detector, particularly the description of the ``garbage`` value.
1244+      cycle detector, particularly the description of the ``garbage`` value.
1206
1207   .. warning::
1208
1209      Due to the precarious circumstances under which :meth:`__del__` methods are
1210      invoked, exceptions that occur during their execution are ignored, and a warning
1211      is printed to ``sys.stderr`` instead.  Also, when :meth:`__del__` is invoked in
1212      response to a module being deleted (e.g., when execution of the program is
1213      done), other globals referenced by the :meth:`__del__` method may already have
n1214-      been deleted.  For this reason, :meth:`__del__` methods should do the absolute
n1253+      been deleted or in the process of being torn down (e.g. the import
1254+      machinery shutting down).  For this reason, :meth:`__del__` methods
1255+      should do the absolute
1215      minimum needed to maintain external invariants.  Starting with version 1.5,
1216      Python guarantees that globals whose name begins with a single underscore are
1217      deleted from their module before other globals are deleted; if no other
1218      references to such globals exist, this may help in assuring that imported
1219      modules are still available at the time when the :meth:`__del__` method is
1220      called.
1221
1222
1261            object.__le__(self, other)
1262            object.__eq__(self, other)
1263            object.__ne__(self, other)
1264            object.__gt__(self, other)
1265            object.__ge__(self, other)
1266
1267   .. versionadded:: 2.1
1268
n1310+   .. index::
1311+      single: comparisons
1312+ 
1269   These are the so-called "rich comparison" methods, and are called for comparison
1270   operators in preference to :meth:`__cmp__` below. The correspondence between
1271   operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
1272   ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and
1273   ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls
n1274-   ``x.__ge__(y)``. These methods can return any value, but if the comparison
n1318+   ``x.__ge__(y)``.
1275-   operator is used in a Boolean context, the return value should be interpretable
1276-   as a Boolean value, else a :exc:`TypeError` will be raised. By convention,
1277-   ``False`` is used for false and ``True`` for true.
1278
n1320+   A rich comparison method may return the singleton ``NotImplemented`` if it does
1321+   not implement the operation for a given pair of arguments. By convention,
1322+   ``False`` and ``True`` are returned for a successful comparison. However, these
1323+   methods can return any value, so if the comparison operator is used in a Boolean
1324+   context (e.g., in the condition of an ``if`` statement), Python will call
1325+   :func:`bool` on the value to determine if the result is true or false.
1326+ 
1279-   There are no implied relationships among the comparison operators. The truth of
1327+   There are no implied relationships among the comparison operators. The truth
1280-   ``x==y`` does not imply that ``x!=y`` is false.  Accordingly, when defining
1328+   of ``x==y`` does not imply that ``x!=y`` is false.  Accordingly, when
1281-   :meth:`__eq__`, one should also define :meth:`__ne__` so that the operators will
1329+   defining :meth:`__eq__`, one should also define :meth:`__ne__` so that the
1282-   behave as expected.
1330+   operators will behave as expected.  See the paragraph on :meth:`__hash__` for
1331+   some important notes on creating :term:`hashable` objects which support
1332+   custom comparison operations and are usable as dictionary keys.
1283
n1284-   There are no reflected (swapped-argument) versions of these methods (to be used
n1334+   There are no swapped-argument versions of these methods (to be used when the
1285-   when the left argument does not support the operation but the right argument
1335+   left argument does not support the operation but the right argument does);
1286-   does); rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
1336+   rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
1287   :meth:`__le__` and :meth:`__ge__` are each other's reflection, and
1288   :meth:`__eq__` and :meth:`__ne__` are their own reflection.
1289
n1290-   Arguments to rich comparison methods are never coerced.  A rich comparison
n1340+   Arguments to rich comparison methods are never coerced.
1291-   method may return ``NotImplemented`` if it does not implement the operation for
1292-   a given pair of arguments.
1293
1294
1295.. method:: object.__cmp__(self, other)
1296
1297   .. index::
1298      builtin: cmp
1299      single: comparisons
1300
n1301-   Called by comparison operations if rich comparison (see above) is not defined.
n1349+   Called by comparison operations if rich comparison (see above) is not
1302-   Should return a negative integer if ``self < other``, zero if ``self == other``,
1350+   defined.  Should return a negative integer if ``self < other``, zero if
1303-   a positive integer if ``self > other``.  If no :meth:`__cmp__`, :meth:`__eq__`
1351+   ``self == other``, a positive integer if ``self > other``.  If no
1304-   or :meth:`__ne__` operation is defined, class instances are compared by object
1352+   :meth:`__cmp__`, :meth:`__eq__` or :meth:`__ne__` operation is defined, class
1305-   identity ("address").  See also the description of :meth:`__hash__` for some
1353+   instances are compared by object identity ("address").  See also the
1306-   important notes on creating objects which support custom comparison operations
1354+   description of :meth:`__hash__` for some important notes on creating
1355+   :term:`hashable` objects which support custom comparison operations and are
1307-   and are usable as dictionary keys. (Note: the restriction that exceptions are
1356+   usable as dictionary keys. (Note: the restriction that exceptions are not
1308-   not propagated by :meth:`__cmp__` has been removed since Python 1.5.)
1357+   propagated by :meth:`__cmp__` has been removed since Python 1.5.)
1309
1310
1311.. method:: object.__rcmp__(self, other)
1312
1313   .. versionchanged:: 2.1
1314      No longer supported.
1315
1316
1317.. method:: object.__hash__(self)
1318
1319   .. index::
1320      object: dictionary
1321      builtin: hash
1322
n1323-   Called for the key object for dictionary  operations, and by the built-in
n1372+   Called by built-in function :func:`hash` and for operations on members of
1324-   function :func:`hash`.  Should return a 32-bit integer usable as a hash value
1373+   hashed collections including :class:`set`, :class:`frozenset`, and
1325-   for dictionary operations.  The only required property is that objects which
1374+   :class:`dict`.  :meth:`__hash__` should return an integer.  The only required
1326-   compare equal have the same hash value; it is advised to somehow mix together
1375+   property is that objects which compare equal have the same hash value; it is
1327-   (e.g., using exclusive or) the hash values for the components of the object that
1376+   advised to somehow mix together (e.g. using exclusive or) the hash values for
1328-   also play a part in comparison of objects.  If a class does not define a
1377+   the components of the object that also play a part in comparison of objects.
1329-   :meth:`__cmp__` method it should not define a :meth:`__hash__` operation either;
1378+ 
1379+   If a class does not define a :meth:`__cmp__` or :meth:`__eq__` method it
1380+   should not define a :meth:`__hash__` operation either; if it defines
1330-   if it defines :meth:`__cmp__` or :meth:`__eq__` but not :meth:`__hash__`, its
1381+   :meth:`__cmp__` or :meth:`__eq__` but not :meth:`__hash__`, its instances
1331-   instances will not be usable as dictionary keys.  If a class defines mutable
1382+   will not be usable in hashed collections.  If a class defines mutable objects
1332-   objects and implements a :meth:`__cmp__` or :meth:`__eq__` method, it should not
1383+   and implements a :meth:`__cmp__` or :meth:`__eq__` method, it should not
1333-   implement :meth:`__hash__`, since the dictionary implementation requires that a
1384+   implement :meth:`__hash__`, since hashablcollection implementations require
1334-   key's hash value is immutable (if the object's hash value changes, it will be in
1385+   that a object's hash value is immutable (if the object's hash value changes,
1335-   the wrong hash bucket).
1386+   it will be in the wrong hash bucket).
1387+ 
1388+   User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods
1389+   by default; with them, all objects compare unequal (except with themselves)
1390+   and ``x.__hash__()`` returns ``id(x)``.
1391+ 
1392+   Classes which inherit a :meth:`__hash__` method from a parent class but
1393+   change the meaning of :meth:`__cmp__` or :meth:`__eq__` such that the hash
1394+   value returned is no longer appropriate (e.g. by switching to a value-based
1395+   concept of equality instead of the default identity based equality) can
1396+   explicitly flag themselves as being unhashable by setting ``__hash__ = None``
1397+   in the class definition. Doing so means that not only will instances of the
1398+   class raise an appropriate :exc:`TypeError` when a program attempts to
1399+   retrieve their hash value, but they will also be correctly identified as
1400+   unhashable when checking ``isinstance(obj, collections.Hashable)`` (unlike
1401+   classes which define their own :meth:`__hash__` to explicitly raise
1402+   :exc:`TypeError`).
1336
1337   .. versionchanged:: 2.5
n1338-      :meth:`__hash__` may now also return a long integer object; the 32-bit integer
n1405+      :meth:`__hash__` may now also return a long integer object; the 32-bit
1339-      is then derived from the hash of that object.
1406+      integer is then derived from the hash of that object.
1340
n1341-   .. index:: single: __cmp__() (object method)
n1408+   .. versionchanged:: 2.6
1409+      :attr:`__hash__` may now be set to :const:`None` to explicitly flag
1410+      instances of a class as unhashable.
1342
1343
1344.. method:: object.__nonzero__(self)
1345
1346   .. index:: single: __len__() (mapping object method)
1347
n1348-   Called to implement truth value testing, and the built-in operation ``bool()``;
n1417+   Called to implement truth value testing and the built-in operation ``bool()``;
1349   should return ``False`` or ``True``, or their integer equivalents ``0`` or
n1350-   ``1``. When this method is not defined, :meth:`__len__` is called, if it is
n1419+   ``1``.  When this method is not defined, :meth:`__len__` is called, if it is
1351-   defined (see below).  If a class defines neither :meth:`__len__` nor
1420+   defined, and the object is considered true if its result is nonzero.
1352-   :meth:`__nonzero__`, all its instances are considered true.
1421+   If a class defines neither :meth:`__len__` nor :meth:`__nonzero__`, all its
1422+   instances are considered true.
1353
1354
1355.. method:: object.__unicode__(self)
1356
1357   .. index:: builtin: unicode
1358
1359   Called to implement :func:`unicode` builtin; should return a Unicode object.
1360   When this method is not defined, string conversion is attempted, and the result
1377   ``self``).  ``name`` is the attribute name. This method should return the
1378   (computed) attribute value or raise an :exc:`AttributeError` exception.
1379
1380   .. index:: single: __setattr__() (object method)
1381
1382   Note that if the attribute is found through the normal mechanism,
1383   :meth:`__getattr__` is not called.  (This is an intentional asymmetry between
1384   :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
n1385-   reasons and because otherwise :meth:`__setattr__` would have no way to access
n1455+   reasons and because otherwise :meth:`__getattr__` would have no way to access
1386   other attributes of the instance.  Note that at least for instance variables,
1387   you can fake total control by not inserting any values in the instance attribute
1388   dictionary (but instead inserting them in another object).  See the
1389   :meth:`__getattribute__` method below for a way to actually get total control in
1390   new-style classes.
1391
1392
1393.. method:: object.__setattr__(self, name, value)
1394
1395   Called when an attribute assignment is attempted.  This is called instead of the
1396   normal mechanism (i.e. store the value in the instance dictionary).  *name* is
1397   the attribute name, *value* is the value to be assigned to it.
1398
1399   .. index:: single: __dict__ (instance attribute)
1400
n1401-   If :meth:`__setattr__` wants to assign to an instance attribute, it  should not
n1471+   If :meth:`__setattr__` wants to assign to an instance attribute, it should not
1402   simply execute ``self.name = value`` --- this would cause a recursive call to
1403   itself.  Instead, it should insert the value in the dictionary of instance
1404   attributes, e.g., ``self.__dict__[name] = value``.  For new-style classes,
1405   rather than accessing the instance dictionary, it should call the base class
1406   method with the same name, for example, ``object.__setattr__(self, name,
1407   value)``.
1408
1409
1419^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1420
1421The following methods only apply to new-style classes.
1422
1423
1424.. method:: object.__getattribute__(self, name)
1425
1426   Called unconditionally to implement attribute accesses for instances of the
n1427-   class. If the class also defines :meth:`__getattr__`, the latter  will not be
n1497+   class. If the class also defines :meth:`__getattr__`, the latter will not be
1428-   called unless :meth:`__getattribute__` either calls it  explicitly or raises an
1498+   called unless :meth:`__getattribute__` either calls it explicitly or raises an
1429   :exc:`AttributeError`. This method should return the (computed) attribute value
1430   or raise an :exc:`AttributeError` exception. In order to avoid infinite
1431   recursion in this method, its implementation should always call the base class
1432   method with the same name to access any attributes it needs, for example,
1433   ``object.__getattribute__(self, name)``.
n1504+ 
1505+   .. note::
1506+ 
1507+      This method may still be bypassed when looking up special methods as the
1508+      result of implicit invocation via language syntax or builtin functions.
1509+      See :ref:`new-style-special-lookup`.
1434
1435
1436.. _descriptors:
1437
1438Implementing Descriptors
1439^^^^^^^^^^^^^^^^^^^^^^^^
1440
1441The following methods only apply when an instance of the class containing the
1475In general, a descriptor is an object attribute with "binding behavior", one
1476whose attribute access has been overridden by methods in the descriptor
1477protocol:  :meth:`__get__`, :meth:`__set__`, and :meth:`__delete__`. If any of
1478those methods are defined for an object, it is said to be a descriptor.
1479
1480The default behavior for attribute access is to get, set, or delete the
1481attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain
1482starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
n1483-continuing  through the base classes of ``type(a)`` excluding metaclasses.
n1559+continuing through the base classes of ``type(a)`` excluding metaclasses.
1484
1485However, if the looked-up value is an object defining one of the descriptor
1486methods, then Python may override the default behavior and invoke the descriptor
1487method instead.  Where this occurs in the precedence chain depends on which
1488descriptor methods were defined and how they were called.  Note that descriptors
1489are only invoked for new style objects or classes (ones that subclass
1490:class:`object()` or :class:`type()`).
1491
1506
1507Super Binding
1508   If ``a`` is an instance of :class:`super`, then the binding ``super(B,
1509   obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A``
1510   immediately preceding ``B`` and then invokes the descriptor with the call:
1511   ``A.__dict__['m'].__get__(obj, A)``.
1512
1513For instance bindings, the precedence of descriptor invocation depends on the
n1514-which descriptor methods are defined.  Data descriptors define both
n1590+which descriptor methods are defined.  Normally, data descriptors define both
1515-:meth:`__get__` and :meth:`__set__`.  Non-data descriptors have just the
1591+:meth:`__get__` and :meth:`__set__`, while non-data descriptors have just the
1516:meth:`__get__` method.  Data descriptors always override a redefinition in an
1517instance dictionary.  In contrast, non-data descriptors can be overridden by
n1518-instances.
n1594+instances. [#]_
1519
1520Python methods (including :func:`staticmethod` and :func:`classmethod`) are
1521implemented as non-data descriptors.  Accordingly, instances can redefine and
1522override methods.  This allows individual instances to acquire behaviors that
1523differ from other instances of the same class.
1524
1525The :func:`property` function is implemented as a data descriptor. Accordingly,
1526instances cannot override the behavior of a property.
1547   This class variable can be assigned a string, iterable, or sequence of strings
1548   with variable names used by instances.  If defined in a new-style class,
1549   *__slots__* reserves space for the declared variables and prevents the automatic
1550   creation of *__dict__* and *__weakref__* for each instance.
1551
1552   .. versionadded:: 2.2
1553
1554Notes on using *__slots__*
n1631+ 
1632+* When inheriting from a class without *__slots__*, the *__dict__* attribute of
1633+  that class will always be accessible, so a *__slots__* definition in the
1634+  subclass is meaningless.
1555
1556* Without a *__dict__* variable, instances cannot be assigned new variables not
1557  listed in the *__slots__* definition.  Attempts to assign to an unlisted
1558  variable name raises :exc:`AttributeError`. If dynamic assignment of new
1559  variables is desired, then add ``'__dict__'`` to the sequence of strings in the
1560  *__slots__* declaration.
1561
1562  .. versionchanged:: 2.3
1583  defined by the base class slot is inaccessible (except by retrieving its
1584  descriptor directly from the base class). This renders the meaning of the
1585  program undefined.  In the future, a check may be added to prevent this.
1586
1587* The action of a *__slots__* declaration is limited to the class where it is
1588  defined.  As a result, subclasses will have a *__dict__* unless they also define
1589  *__slots__*.
1590
n1591-* *__slots__* do not work for classes derived from "variable-length" built-in
n1671+* Nonempty *__slots__* does not work for classes derived from "variable-length"
1592-  types such as :class:`long`, :class:`str` and :class:`tuple`.
1672+  built-in types such as :class:`long`, :class:`str` and :class:`tuple`.
1593
1594* Any non-string iterable may be assigned to *__slots__*. Mappings may also be
1595  used; however, in the future, special meaning may be assigned to the values
1596  corresponding to each key.
1597
n1678+* *__class__* assignment works only if both classes have the same *__slots__*.
1679+ 
1680+  .. versionchanged:: 2.6
1681+     Previously, *__class__* assignment raised an error if either new or old class
1682+     had *__slots__*.
1683+ 
1598
1599.. _metaclasses:
1600
1601Customizing class creation
1602--------------------------
1603
1604By default, new-style classes are constructed using :func:`type`. A class
1605definition is read into a separate namespace and the value of class name is
1606bound to the result of ``type(name, bases, dict)``.
1607
1608When the class definition is read, if *__metaclass__* is defined then the
n1609-callable assigned to it will be called instead of :func:`type`. The allows
n1695+callable assigned to it will be called instead of :func:`type`. This allows
1610classes or functions to be written which monitor or alter the class creation
1611process:
1612
1613* Modifying the class dictionary prior to the class being created.
1614
1615* Returning an instance of another class -- essentially performing the role of a
1616  factory function.
n1703+ 
1704+These steps will have to be performed in the metaclass's :meth:`__new__` method
1705+-- :meth:`type.__new__` can then be called from this method to create a class
1706+with different properties.  This example adds a new element to the class
1707+dictionary before creating the class::
1708+ 
1709+  class metacls(type):
1710+      def __new__(mcs, name, bases, dict):
1711+          dict['foo'] = 'metacls was here'
1712+          return type.__new__(mcs, name, bases, dict)
1713+ 
1714+You can of course also override other class methods (or add new methods); for
1715+example defining a custom :meth:`__call__` method in the metaclass allows custom
1716+behavior when the class is called, e.g. not always creating a new instance.
1617
1618
1619.. data:: __metaclass__
1620
1621   This variable can be any callable accepting arguments for ``name``, ``bases``,
1622   and ``dict``.  Upon class creation, the callable is used instead of the built-in
1623   :func:`type`.
1624
1654   Called when the instance is "called" as a function; if this method is defined,
1655   ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``.
1656
1657
1658.. _sequence-types:
1659
1660Emulating container types
1661-------------------------
n1662- 
1663-.. index::
1664-   single: keys() (mapping object method)
1665-   single: values() (mapping object method)
1666-   single: items() (mapping object method)
1667-   single: iterkeys() (mapping object method)
1668-   single: itervalues() (mapping object method)
1669-   single: iteritems() (mapping object method)
1670-   single: has_key() (mapping object method)
1671-   single: get() (mapping object method)
1672-   single: setdefault() (mapping object method)
1673-   single: pop() (mapping object method)
1674-   single: popitem() (mapping object method)
1675-   single: clear() (mapping object method)
1676-   single: copy() (mapping object method)
1677-   single: update() (mapping object method)
1678-   single: __contains__() (mapping object method)
1679-   single: append() (sequence object method)
1680-   single: count() (sequence object method)
1681-   single: extend() (sequence object method)
1682-   single: index() (sequence object method)
1683-   single: insert() (sequence object method)
1684-   single: pop() (sequence object method)
1685-   single: remove() (sequence object method)
1686-   single: reverse() (sequence object method)
1687-   single: sort() (sequence object method)
1688-   single: __add__() (sequence object method)
1689-   single: __radd__() (sequence object method)
1690-   single: __iadd__() (sequence object method)
1691-   single: __mul__() (sequence object method)
1692-   single: __rmul__() (sequence object method)
1693-   single: __imul__() (sequence object method)
1694-   single: __contains__() (sequence object method)
1695-   single: __iter__() (sequence object method)
1696-   single: __coerce__() (numeric object method)
1697
1698The following methods can be defined to implement container objects.  Containers
1699usually are sequences (such as lists or tuples) or mappings (like dictionaries),
1700but can represent other containers as well.  The first set of methods is used
1701either to emulate a sequence or to emulate a mapping; the difference is that for
1702a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
1703N`` where *N* is the length of the sequence, or slice objects, which define a
1704range of items. (For backwards compatibility, the method :meth:`__getslice__`
1705(see below) can also be defined to handle simple, but not extended slices.) It
1706is also recommended that mappings provide the methods :meth:`keys`,
1707:meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, :meth:`clear`,
1708:meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, :meth:`iteritems`,
n1709-:meth:`pop`, :meth:`popitem`,                 :meth:`copy`, and :meth:`update`
n1774+:meth:`pop`, :meth:`popitem`, :meth:`copy`, and :meth:`update` behaving similar
1710-behaving similar to those for Python's standard dictionary objects.  The
1775+to those for Python's standard dictionary objects.  The :mod:`UserDict` module
1711-:mod:`UserDict` module provides a :class:`DictMixin` class to help create those
1776+provides a :class:`DictMixin` class to help create those methods from a base set
1712-methods from a base set of :meth:`__getitem__`, :meth:`__setitem__`,
1777+of :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and
1713-:meth:`__delitem__`, and :meth:`keys`.                   Mutable sequences
1778+:meth:`keys`. Mutable sequences should provide methods :meth:`append`,
1714-should provide methods :meth:`append`, :meth:`count`, :meth:`index`,
1779+:meth:`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`,
1715-:meth:`extend`,                  :meth:`insert`, :meth:`pop`, :meth:`remove`,
1716-:meth:`reverse` and :meth:`sort`, like Python standard list objects.  Finally,
1780+:meth:`remove`, :meth:`reverse` and :meth:`sort`, like Python standard list
1717-sequence types should implement addition (meaning concatenation) and
1781+objects.  Finally, sequence types should implement addition (meaning
1718-multiplication (meaning repetition) by defining the methods :meth:`__add__`,
1782+concatenation) and multiplication (meaning repetition) by defining the methods
1719-:meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`, :meth:`__rmul__` and
1783+:meth:`__add__`, :meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`,
1720-:meth:`__imul__` described below; they should not define :meth:`__coerce__` or
1784+:meth:`__rmul__` and :meth:`__imul__` described below; they should not define
1721-other numerical operators.  It is recommended that both mappings and sequences
1785+:meth:`__coerce__` or other numerical operators.  It is recommended that both
1722-implement the :meth:`__contains__` method to allow efficient use of the ``in``
1723-operator; for mappings, ``in`` should be equivalent of :meth:`has_key`; for
1724-sequences, it should search through the values.  It is further recommended that
1725-both mappings and sequences implement the :meth:`__iter__` method to allow
1786+mappings and sequences implement the :meth:`__contains__` method to allow
1726-efficient iteration through the container; for mappings, :meth:`__iter__` should
1787+efficient use of the ``in`` operator; for mappings, ``in`` should be equivalent
1727-be the same as :meth:`iterkeys`; for sequences, it should iterate through the
1788+of :meth:`has_key`; for sequences, it should search through the values.  It is
1728-values.
1789+further recommended that both mappings and sequences implement the
1790+:meth:`__iter__` method to allow efficient iteration through the container; for
1791+mappings, :meth:`__iter__` should be the same as :meth:`iterkeys`; for
1792+sequences, it should iterate through the values.
1729
1730
n1731-.. method:: container object.__len__(self)
n1795+.. method:: object.__len__(self)
1732
1733   .. index::
1734      builtin: len
1735      single: __nonzero__() (object method)
1736
1737   Called to implement the built-in function :func:`len`.  Should return the length
1738   of the object, an integer ``>=`` 0.  Also, an object that doesn't define a
1739   :meth:`__nonzero__` method and whose :meth:`__len__` method returns zero is
1740   considered to be false in a Boolean context.
1741
1742
n1743-.. method:: container object.__getitem__(self, key)
n1807+.. method:: object.__getitem__(self, key)
1744
1745   .. index:: object: slice
1746
1747   Called to implement evaluation of ``self[key]``. For sequence types, the
1748   accepted keys should be integers and slice objects.  Note that the special
1749   interpretation of negative indexes (if the class wishes to emulate a sequence
1750   type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate
1751   type, :exc:`TypeError` may be raised; if of a value outside the set of indexes
1754   in the container), :exc:`KeyError` should be raised.
1755
1756   .. note::
1757
1758      :keyword:`for` loops expect that an :exc:`IndexError` will be raised for illegal
1759      indexes to allow proper detection of the end of the sequence.
1760
1761
n1762-.. method:: container object.__setitem__(self, key, value)
n1826+.. method:: object.__setitem__(self, key, value)
1763
1764   Called to implement assignment to ``self[key]``.  Same note as for
1765   :meth:`__getitem__`.  This should only be implemented for mappings if the
1766   objects support changes to the values for keys, or if new keys can be added, or
1767   for sequences if elements can be replaced.  The same exceptions should be raised
1768   for improper *key* values as for the :meth:`__getitem__` method.
1769
1770
n1771-.. method:: container object.__delitem__(self, key)
n1835+.. method:: object.__delitem__(self, key)
1772
1773   Called to implement deletion of ``self[key]``.  Same note as for
1774   :meth:`__getitem__`.  This should only be implemented for mappings if the
1775   objects support removal of keys, or for sequences if elements can be removed
1776   from the sequence.  The same exceptions should be raised for improper *key*
1777   values as for the :meth:`__getitem__` method.
1778
1779
n1780-.. method:: container object.__iter__(self)
n1844+.. method:: object.__iter__(self)
1781
1782   This method is called when an iterator is required for a container. This method
1783   should return a new iterator object that can iterate over all the objects in the
1784   container.  For mappings, it should iterate over the keys of the container, and
1785   should also be made available as the method :meth:`iterkeys`.
1786
1787   Iterator objects also need to implement this method; they are required to return
n1788-   themselves.  For more information on iterator objects, see "Iterator Types (XXX
n1852+   themselves.  For more information on iterator objects, see :ref:`typeiter`.
1789-   reference: ../lib/typeiter.html)" in the Python Library Reference (XXX
1853+ 
1790-   reference: ../lib/lib.html).
1854+ 
1855+.. method:: object.__reversed__(self)
1856+ 
1857+   Called (if present) by the :func:`reversed` builtin to implement
1858+   reverse iteration.  It should return a new iterator object that iterates
1859+   over all the objects in the container in reverse order.
1860+ 
1861+   If the :meth:`__reversed__` method is not provided, the
1862+   :func:`reversed` builtin will fall back to using the sequence protocol
1863+   (:meth:`__len__` and :meth:`__getitem__`).  Objects should normally
1864+   only provide :meth:`__reversed__` if they do not support the sequence
1865+   protocol and an efficient implementation of reverse iteration is possible.
1866+ 
1867+   .. versionadded:: 2.6
1868+ 
1791
1792The membership test operators (:keyword:`in` and :keyword:`not in`) are normally
1793implemented as an iteration through a sequence.  However, container objects can
1794supply the following special method with a more efficient implementation, which
1795also does not require the object be a sequence.
1796
1797
n1798-.. method:: container object.__contains__(self, item)
n1876+.. method:: object.__contains__(self, item)
1799
1800   Called to implement membership test operators.  Should return true if *item* is
1801   in *self*, false otherwise.  For mapping objects, this should consider the keys
1802   of the mapping rather than the values or the key-item pairs.
1803
1804
1805.. _sequence-methods:
1806
1807Additional methods for emulation of sequence types
1808--------------------------------------------------
1809
1810The following optional methods can be defined to further emulate sequence
1811objects.  Immutable sequences methods should at most only define
1812:meth:`__getslice__`; mutable sequences might define all three methods.
1813
1814
n1815-.. method:: sequence object.__getslice__(self, i, j)
n1893+.. method:: object.__getslice__(self, i, j)
1816
1817   .. deprecated:: 2.0
1818      Support slice objects as parameters to the :meth:`__getitem__` method.
n1897+      (However, built-in types in CPython currently still implement
1898+      :meth:`__getslice__`.  Therefore, you have to override it in derived
1899+      classes when implementing slicing.)
1819
1820   Called to implement evaluation of ``self[i:j]``. The returned object should be
1821   of the same type as *self*.  Note that missing *i* or *j* in the slice
1822   expression are replaced by zero or ``sys.maxint``, respectively.  If negative
1823   indexes are used in the slice, the length of the sequence is added to that
1824   index. If the instance does not implement the :meth:`__len__` method, an
1825   :exc:`AttributeError` is raised. No guarantee is made that indexes adjusted this
1826   way are not still negative.  Indexes which are greater than the length of the
1827   sequence are not modified. If no :meth:`__getslice__` is found, a slice object
1828   is created instead, and passed to :meth:`__getitem__` instead.
1829
1830
n1831-.. method:: sequence object.__setslice__(self, i, j, sequence)
n1912+.. method:: object.__setslice__(self, i, j, sequence)
1832
1833   Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as
1834   for :meth:`__getslice__`.
1835
1836   This method is deprecated. If no :meth:`__setslice__` is found, or for extended
1837   slicing of the form ``self[i:j:k]``, a slice object is created, and passed to
1838   :meth:`__setitem__`, instead of :meth:`__setslice__` being called.
1839
1840
n1841-.. method:: sequence object.__delslice__(self, i, j)
n1922+.. method:: object.__delslice__(self, i, j)
1842
1843   Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for
1844   :meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
1845   found, or for extended slicing of the form ``self[i:j:k]``, a slice object is
1846   created, and passed to :meth:`__delitem__`, instead of :meth:`__delslice__`
1847   being called.
1848
1849Notice that these methods are only invoked when a single slice with a single
1897-----------------------
1898
1899The following methods can be defined to emulate numeric objects. Methods
1900corresponding to operations that are not supported by the particular kind of
1901number implemented (e.g., bitwise operations for non-integral numbers) should be
1902left undefined.
1903
1904
n1905-.. method:: numeric object.__add__(self, other)
n1986+.. method:: object.__add__(self, other)
1906-            numeric object.__sub__(self, other)
1987+            object.__sub__(self, other)
1907-            numeric object.__mul__(self, other)
1988+            object.__mul__(self, other)
1908-            numeric object.__floordiv__(self, other)
1989+            object.__floordiv__(self, other)
1909-            numeric object.__mod__(self, other)
1990+            object.__mod__(self, other)
1910-            numeric object.__divmod__(self, other)
1991+            object.__divmod__(self, other)
1911-            numeric object.__pow__(self, other[, modulo])
1992+            object.__pow__(self, other[, modulo])
1912-            numeric object.__lshift__(self, other)
1993+            object.__lshift__(self, other)
1913-            numeric object.__rshift__(self, other)
1994+            object.__rshift__(self, other)
1914-            numeric object.__and__(self, other)
1995+            object.__and__(self, other)
1915-            numeric object.__xor__(self, other)
1996+            object.__xor__(self, other)
1916-            numeric object.__or__(self, other)
1997+            object.__or__(self, other)
1917
1918   .. index::
1919      builtin: divmod
1920      builtin: pow
1921      builtin: pow
1922
1923   These methods are called to implement the binary arithmetic operations (``+``,
1924   ``-``, ``*``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``,
1925   ``>>``, ``&``, ``^``, ``|``).  For instance, to evaluate the expression
n1926-   *x*``+``*y*, where *x* is an instance of a class that has an :meth:`__add__`
n2007+   ``+ y``, where *x* is an instance of a class that has an :meth:`__add__`
1927   method, ``x.__add__(y)`` is called.  The :meth:`__divmod__` method should be the
1928   equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be
1929   related to :meth:`__truediv__` (described below).  Note that :meth:`__pow__`
1930   should be defined to accept an optional third argument if the ternary version of
1931   the built-in :func:`pow` function is to be supported.
1932
1933   If one of those methods does not support the operation with the supplied
1934   arguments, it should return ``NotImplemented``.
1935
1936
n1937-.. method:: numeric object.__div__(self, other)
n2018+.. method:: object.__div__(self, other)
1938-            numeric object.__truediv__(self, other)
2019+            object.__truediv__(self, other)
1939
1940   The division operator (``/``) is implemented by these methods.  The
1941   :meth:`__truediv__` method is used when ``__future__.division`` is in effect,
1942   otherwise :meth:`__div__` is used.  If only one of these two methods is defined,
1943   the object will not support division in the alternate context; :exc:`TypeError`
1944   will be raised instead.
1945
1946
n1947-.. method:: numeric object.__radd__(self, other)
n2028+.. method:: object.__radd__(self, other)
1948-            numeric object.__rsub__(self, other)
2029+            object.__rsub__(self, other)
1949-            numeric object.__rmul__(self, other)
2030+            object.__rmul__(self, other)
1950-            numeric object.__rdiv__(self, other)
2031+            object.__rdiv__(self, other)
1951-            numeric object.__rtruediv__(self, other)
2032+            object.__rtruediv__(self, other)
1952-            numeric object.__rfloordiv__(self, other)
2033+            object.__rfloordiv__(self, other)
1953-            numeric object.__rmod__(self, other)
2034+            object.__rmod__(self, other)
1954-            numeric object.__rdivmod__(self, other)
2035+            object.__rdivmod__(self, other)
1955-            numeric object.__rpow__(self, other)
2036+            object.__rpow__(self, other)
1956-            numeric object.__rlshift__(self, other)
2037+            object.__rlshift__(self, other)
1957-            numeric object.__rrshift__(self, other)
2038+            object.__rrshift__(self, other)
1958-            numeric object.__rand__(self, other)
2039+            object.__rand__(self, other)
1959-            numeric object.__rxor__(self, other)
2040+            object.__rxor__(self, other)
1960-            numeric object.__ror__(self, other)
2041+            object.__ror__(self, other)
1961
1962   .. index::
1963      builtin: divmod
1964      builtin: pow
1965
1966   These methods are called to implement the binary arithmetic operations (``+``,
1967   ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``,
1968   ``&``, ``^``, ``|``) with reflected (swapped) operands.  These functions are
1969   only called if the left operand does not support the corresponding operation and
n1970-   the operands are of different types. [#]_  For instance, to evaluate the
n2051+   the operands are of different types. [#]_ For instance, to evaluate the
1971-   expression *x*``-``*y*, where *y* is an instance of a class that has an
2052+   expression ``- y``, where *y* is an instance of a class that has an
1972   :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns
1973   *NotImplemented*.
1974
1975   .. index:: builtin: pow
1976
1977   Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
1978   coercion rules would become too complicated).
1979
1980   .. note::
1981
1982      If the right operand's type is a subclass of the left operand's type and that
1983      subclass provides the reflected method for the operation, this method will be
1984      called before the left operand's non-reflected method.  This behavior allows
1985      subclasses to override their ancestors' operations.
1986
1987
n1988-.. method:: numeric object.__iadd__(self, other)
n2069+.. method:: object.__iadd__(self, other)
1989-            numeric object.__isub__(self, other)
2070+            object.__isub__(self, other)
1990-            numeric object.__imul__(self, other)
2071+            object.__imul__(self, other)
1991-            numeric object.__idiv__(self, other)
2072+            object.__idiv__(self, other)
1992-            numeric object.__itruediv__(self, other)
2073+            object.__itruediv__(self, other)
1993-            numeric object.__ifloordiv__(self, other)
2074+            object.__ifloordiv__(self, other)
1994-            numeric object.__imod__(self, other)
2075+            object.__imod__(self, other)
1995-            numeric object.__ipow__(self, other[, modulo])
2076+            object.__ipow__(self, other[, modulo])
1996-            numeric object.__ilshift__(self, other)
2077+            object.__ilshift__(self, other)
1997-            numeric object.__irshift__(self, other)
2078+            object.__irshift__(self, other)
1998-            numeric object.__iand__(self, other)
2079+            object.__iand__(self, other)
1999-            numeric object.__ixor__(self, other)
2080+            object.__ixor__(self, other)
2000-            numeric object.__ior__(self, other)
2081+            object.__ior__(self, other)
2001
n2002-   These methods are called to implement the augmented arithmetic operations
n2083+   These methods are called to implement the augmented arithmetic assignments
2003-   (``+=``, ``-=``, ``*=``, ``/=``, ``%=``, ``**=``, ``<<=``, ``>>=``, ``&=``,
2084+   (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
2004-   ``^=``, ``|=``).  These methods should attempt to do the operation in-place
2085+   ``&=``, ``^=``, ``|=``).  These methods should attempt to do the operation
2005-   (modifying *self*) and return the result (which could be, but does not have to
2086+   in-place (modifying *self*) and return the result (which could be, but does
2006-   be, *self*).  If a specific method is not defined, the augmented operation falls
2087+   not have to be, *self*).  If a specific method is not defined, the augmented
2007-   back to the normal methods.  For instance, to evaluate the expression
2088+   assignment falls back to the normal methods.  For instance, to execute the
2008-   *x*``+=``*y*, where *x* is an instance of a class that has an :meth:`__iadd__`
2089+   statement ``+= y``, where *x* is an instance of a class that has an
2009-   method, ``x.__iadd__(y)`` is called.  If *x* is an instance of a class that does
2090+   :meth:`__iadd__` method, ``x.__iadd__(y)`` is called.  If *x* is an instance
2010-   not define a :meth:`__iadd__` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are
2091+   of a class that does not define a :meth:`__iadd__` method, ``x.__add__(y)``
2011-   considered, as with the evaluation of *x*``+``*y*.
2092+   and ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``.
2012
2013
n2014-.. method:: numeric object.__neg__(self)
n2095+.. method:: object.__neg__(self)
2015-            numeric object.__pos__(self)
2096+            object.__pos__(self)
2016-            numeric object.__abs__(self)
2097+            object.__abs__(self)
2017-            numeric object.__invert__(self)
2098+            object.__invert__(self)
2018
2019   .. index:: builtin: abs
2020
2021   Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
2022   and ``~``).
2023
2024
n2025-.. method:: numeric object.__complex__(self)
n2106+.. method:: object.__complex__(self)
2026-            numeric object.__int__(self)
2107+            object.__int__(self)
2027-            numeric object.__long__(self)
2108+            object.__long__(self)
2028-            numeric object.__float__(self)
2109+            object.__float__(self)
2029
2030   .. index::
2031      builtin: complex
2032      builtin: int
2033      builtin: long
2034      builtin: float
2035
2036   Called to implement the built-in functions :func:`complex`, :func:`int`,
2037   :func:`long`, and :func:`float`.  Should return a value of the appropriate type.
2038
2039
n2040-.. method:: numeric object.__oct__(self)
n2121+.. method:: object.__oct__(self)
2041-            numeric object.__hex__(self)
2122+            object.__hex__(self)
2042
2043   .. index::
2044      builtin: oct
2045      builtin: hex
2046
2047   Called to implement the built-in functions :func:`oct` and :func:`hex`.  Should
2048   return a string value.
2049
2050
n2051-.. method:: numeric object.__index__(self)
n2132+.. method:: object.__index__(self)
2052
2053   Called to implement :func:`operator.index`.  Also called whenever Python needs
2054   an integer object (such as in slicing).  Must return an integer (int or long).
2055
2056   .. versionadded:: 2.5
2057
2058
n2059-.. method:: numeric object.__coerce__(self, other)
n2140+.. method:: object.__coerce__(self, other)
2060
2061   Called to implement "mixed-mode" numeric arithmetic.  Should either return a
2062   2-tuple containing *self* and *other* converted to a common numeric type, or
2063   ``None`` if conversion is impossible.  When the common type would be the type of
2064   ``other``, it is sufficient to return ``None``, since the interpreter will also
2065   ask the other object to attempt a coercion (but sometimes, if the implementation
2066   of the other type cannot be changed, it is useful to do the conversion to the
2067   other type here).  A return value of ``NotImplemented`` is equivalent to
2141
2142  When an in-place operator (like '``+=``') is used, if the left operand
2143  implements :meth:`__iop__`, it is invoked without any coercion.  When the
2144  operation falls back to :meth:`__op__` and/or :meth:`__rop__`, the normal
2145  coercion rules apply.
2146
2147*
2148
n2149-  In *x*``+``*y*, if *x* is a sequence that implements sequence concatenation,
n2230+  In ``x + y``, if *x* is a sequence that implements sequence concatenation,
2150  sequence concatenation is invoked.
2151
2152*
2153
n2154-  In *x*``*``*y*, if one operator is a sequence that implements sequence
n2235+  In ``* y``, if one operator is a sequence that implements sequence
2155  repetition, and the other is an integer (:class:`int` or :class:`long`),
2156  sequence repetition is invoked.
2157
2158*
2159
2160  Rich comparisons (implemented by methods :meth:`__eq__` and so on) never use
2161  coercion.  Three-way comparison (implemented by :meth:`__cmp__`) does use
2162  coercion under the same conditions as other binary operations use it.
2163
2164*
2165
2166  In the current implementation, the built-in numeric types :class:`int`,
2167  :class:`long` and :class:`float` do not use coercion; the type :class:`complex`
n2249+  however does use coercion for binary operators and rich comparisons, despite
2168-  however does use it.  The difference can become apparent when subclassing these
2250+  the above rules.  The difference can become apparent when subclassing these
2169  types.  Over time, the type :class:`complex` may be fixed to avoid coercion.
2170  All these types implement a :meth:`__coerce__` method, for use by the built-in
2171  :func:`coerce` function.
2172
2173
2174.. _context-managers:
2175
2176With Statement Context Managers
2187
2188.. index::
2189   statement: with
2190   single: context manager
2191
2192Typical uses of context managers include saving and restoring various kinds of
2193global state, locking and unlocking resources, closing opened files, etc.
2194
n2195-For more information on context managers, see "Context Types (XXX reference:
n2277+For more information on context managers, see :ref:`typecontextmanager`.
2196-../lib/typecontextmanager.html)" in the Python Library Reference (XXX reference:
2197-../lib/lib.html).
2198
2199
n2200-.. method:: context manager.__enter__(self)
n2280+.. method:: object.__enter__(self)
2201
2202   Enter the runtime context related to this object. The :keyword:`with` statement
2203   will bind this method's return value to the target(s) specified in the
2204   :keyword:`as` clause of the statement, if any.
2205
2206
n2207-.. method:: context manager.__exit__(self, exc_type, exc_value, traceback)
n2287+.. method:: object.__exit__(self, exc_type, exc_value, traceback)
2208
2209   Exit the runtime context related to this object. The parameters describe the
2210   exception that caused the context to be exited. If the context was exited
2211   without an exception, all three arguments will be :const:`None`.
2212
2213   If an exception is supplied, and the method wishes to suppress the exception
2214   (i.e., prevent it from being propagated), it should return a true value.
2215   Otherwise, the exception will be processed normally upon exit from this method.
2219
2220
2221.. seealso::
2222
2223   :pep:`0343` - The "with" statement
2224      The specification, background, and examples for the Python :keyword:`with`
2225      statement.
2226
n2307+ 
2308+.. _old-style-special-lookup:
2309+ 
2310+Special method lookup for old-style classes
2311+-------------------------------------------
2312+ 
2313+For old-style classes, special methods are always looked up in exactly the
2314+same way as any other method or attribute. This is the case regardless of
2315+whether the method is being looked up explicitly as in ``x.__getitem__(i)``
2316+or implicitly as in ``x[i]``.
2317+ 
2318+This behaviour means that special methods may exhibit different behaviour
2319+for different instances of a single old-style class if the appropriate
2320+special attributes are set differently::
2321+ 
2322+   >>> class C:
2323+   ...     pass
2324+   ...
2325+   >>> c1 = C()
2326+   >>> c2 = C()
2327+   >>> c1.__len__ = lambda: 5
2328+   >>> c2.__len__ = lambda: 9
2329+   >>> len(c1)
2330+   5
2331+   >>> len(c2)
2332+   9
2333+ 
2334+ 
2335+.. _new-style-special-lookup:
2336+ 
2337+Special method lookup for new-style classes
2338+-------------------------------------------
2339+ 
2340+For new-style classes, implicit invocations of special methods are only guaranteed
2341+to work correctly if defined on an object's type, not in the object's instance
2342+dictionary.  That behaviour is the reason why the following code raises an
2343+exception (unlike the equivalent example with old-style classes)::
2344+ 
2345+   >>> class C(object):
2346+   ...     pass
2347+   ...
2348+   >>> c = C()
2349+   >>> c.__len__ = lambda: 5
2350+   >>> len(c)
2351+   Traceback (most recent call last):
2352+     File "<stdin>", line 1, in <module>
2353+   TypeError: object of type 'C' has no len()
2354+ 
2355+The rationale behind this behaviour lies with a number of special methods such
2356+as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects,
2357+including type objects. If the implicit lookup of these methods used the
2358+conventional lookup process, they would fail when invoked on the type object
2359+itself::
2360+ 
2361+   >>> 1 .__hash__() == hash(1)
2362+   True
2363+   >>> int.__hash__() == hash(int)
2364+   Traceback (most recent call last):
2365+     File "<stdin>", line 1, in <module>
2366+   TypeError: descriptor '__hash__' of 'int' object needs an argument
2367+ 
2368+Incorrectly attempting to invoke an unbound method of a class in this way is
2369+sometimes referred to as 'metaclass confusion', and is avoided by bypassing
2370+the instance when looking up special methods::
2371+ 
2372+   >>> type(1).__hash__(1) == hash(1)
2373+   True
2374+   >>> type(int).__hash__(int) == hash(int)
2375+   True
2376+ 
2377+In addition to bypassing any instance attributes in the interest of
2378+correctness, implicit special method lookup generally also bypasses the
2379+:meth:`__getattribute__` method even of the object's metaclass::
2380+ 
2381+   >>> class Meta(type):
2382+   ...    def __getattribute__(*args):
2383+   ...       print "Metaclass getattribute invoked"
2384+   ...       return type.__getattribute__(*args)
2385+   ...
2386+   >>> class C(object):
2387+   ...     __metaclass__ = Meta
2388+   ...     def __len__(self):
2389+   ...         return 10
2390+   ...     def __getattribute__(*args):
2391+   ...         print "Class getattribute invoked"
2392+   ...         return object.__getattribute__(*args)
2393+   ...
2394+   >>> c = C()
2395+   >>> c.__len__()                 # Explicit lookup via instance
2396+   Class getattribute invoked
2397+   10
2398+   >>> type(c).__len__(c)          # Explicit lookup via type
2399+   Metaclass getattribute invoked
2400+   10
2401+   >>> len(c)                      # Implicit lookup
2402+   10
2403+ 
2404+Bypassing the :meth:`__getattribute__` machinery in this fashion
2405+provides significant scope for speed optimisations within the
2406+interpreter, at the cost of some flexibility in the handling of
2407+special methods (the special method *must* be set on the class
2408+object itself in order to be consistently invoked by the interpreter).
2409+ 
2410+ 
2227.. rubric:: Footnotes
2228
n2229-.. [#] Since Python 2.2, a gradual merging of types and classes has been started that
n2413+.. [#] It *is* possible in some cases to change an object's type, under certain
2230-   makes this and a few other assertions made in this manual not 100% accurate and
2414+   controlled conditions. It generally isn't a good idea though, since it can
2231-   complete: for example, it *is* now possible in some cases to change an object's
2415+   lead to some very strange behaviour if it is handled incorrectly.
2232-   type, under certain controlled conditions.  Until this manual undergoes
2233-   extensive revision, it must now be taken as authoritative only regarding
2234-   "classic classes", that are still the default, for compatibility purposes, in
2235-   Python 2.2 and 2.3.  For more information, see
2236-   `<http://www.python.org/doc/newstyle.html>`_.
2237
t2238-.. [#] This, and other statements, are only roughly true for instances of new-style
t2417+.. [#] A descriptor can define any combination of :meth:`__get__`,
2239-   classes.
2418+   :meth:`__set__` and :meth:`__delete__`.  If it does not define :meth:`__get__`,
2419+   then accessing the attribute even on an instance will return the descriptor
2420+   object itself.  If the descriptor defines :meth:`__set__` and/or
2421+   :meth:`__delete__`, it is a data descriptor; if it defines neither, it is a
2422+   non-data descriptor.
2240
2241.. [#] For operands of the same type, it is assumed that if the non-reflected method
2242   (such as :meth:`__add__`) fails the operation is not supported, which is why the
2243   reflected method is not called.
2244
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op