Lines Matching +full:is +full:- +full:builtin +full:- +full:module
19 is represented by objects or by relations between objects. (In a sense, and in
20 conformance to Von Neumann's model of a "stored program computer," code is also
24 builtin: id
25 builtin: type
34 memory. The ':keyword:`is`' operator compares the identity of two objects; the
36 implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
39 type. The :func:`type` function returns an object's type (which is an object
41 change are said to be *mutable*; objects whose value is unchangeable once they
44 is changed; however the container is still considered immutable, because the
45 collection of objects it contains cannot be changed. So, immutability is not
46 strictly the same as having an unchangeable value, it is more subtle.) An
47 object's mutability is determined by its type; for instance, numbers, strings
56 they may be garbage-collected. An implementation is allowed to postpone garbage
57 collection or omit it altogether --- it is a matter of implementation quality
58 how garbage collection is implemented, as long as no objects are collected that
61 .. impl-detail::
63 CPython currently uses a reference-counting scheme with (optional) delayed
65 as they become unreachable, but is not guaranteed to collect garbage
67 module for information on controlling the collection of cyclic garbage.
78 windows. It is understood that these resources are freed when the object is
79 garbage-collected, but since garbage collection is not guaranteed to happen,
94 that mutable object is changed.
97 object identity is affected in some sense: for immutable types, operations that
99 the same type and value, while for mutable objects this is not allowed. E.g.,
116 pair: extension; module
119 Below is a list of the types that are built into Python. Extension modules
136 This type has a single value. There is a single object with this value. This
137 object is accessed through the built-in name ``None``. It is used to signify the
138 absence of a value in many situations, e.g., it is returned from functions that
139 don't explicitly return anything. Its truth value is false.
144 This type has a single value. There is a single object with this value. This
145 object is accessed through the built-in name ``NotImplemented``. Numeric methods
149 truth value is true.
154 This type has a single value. There is a single object with this value. This
155 object is accessed through the built-in name ``Ellipsis``. It is used to
156 indicate the presence of the ``...`` syntax in a slice. Its truth value is
163 operators and arithmetic built-in functions. Numeric objects are immutable;
182 single: OverflowError (built-in exception)
184 These represent numbers in the range -2147483648 through 2147483647.
187 this range, the result is normally returned as a long integer (in some
188 cases, the exception :exc:`OverflowError` is raised instead). For the
199 binary representation is assumed, and negative numbers are represented
211 The Boolean type is a subtype of plain integers, and Boolean values
223 when using mixed operands. The switch between domains is transparent to
233 These represent machine-level double precision floating point numbers. You are
236 support single-precision floating point numbers; the savings in processor and
238 overhead of using objects in Python, so there is no reason to complicate the
246 These represent complex numbers as a pair of machine-level double precision
249 the read-only attributes ``z.real`` and ``z.imag``.
253 builtin: len
259 These represent finite ordered sets indexed by non-negative numbers. The
260 built-in function :func:`len` returns the number of items of a sequence. When
261 the length of a sequence is *n*, the index set contains the numbers 0, 1,
262 ..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``.
267 that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a
268 sequence of the same type. This implies that the index set is renumbered so
284 An object of an immutable sequence type cannot change once it is created. (If
293 builtin: chr
294 builtin: ord
300 The items of a string are characters. There is no separate character type; a
301 character is represented by a string of one item. Characters represent (at
302 least) 8-bit bytes. The built-in functions :func:`chr` and :func:`ord` convert
304 with the values 0--127 usually represent the corresponding ASCII values, but the
305 interpretation of values is up to the program. The string data type is also
313 builtin: chr
314 builtin: ord
316 (On systems whose native character set is not ASCII, strings may use EBCDIC in
323 builtin: unichr
324 builtin: ord
325 builtin: unicode
331 The items of a Unicode object are Unicode code units. A Unicode code unit is
332 represented by a Unicode object of one item and can hold either a 16-bit or
333 32-bit value representing a Unicode ordinal (the maximum value for the ordinal
334 is given in ``sys.maxunicode``, and depends on how Python is configured at
336 be reported as two separate items. The built-in functions :func:`unichr` and
340 built-in function :func:`unicode`.
349 are formed by comma-separated lists of expressions. A tuple of one item (a
372 comma-separated list of expressions in square brackets. (Note that there are no
378 A bytearray object is a mutable array. They are created by the built-in
383 .. index:: module: array
385 The extension module :mod:`array` provides an additional example of a mutable
390 builtin: len
395 the built-in function :func:`len` returns the number of items in a set. Common
410 These represent a mutable set. They are created by the built-in :func:`set`
417 These represent an immutable set. They are created by the built-in
418 :func:`frozenset` constructor. As a frozenset is immutable and
424 builtin: len
431 :keyword:`del` statements. The built-in function :func:`len` returns the number
434 There is currently a single intrinsic mapping type:
452 module: dbm
453 module: gdbm
454 module: bsddb
469 User-defined functions
471 pair: user-defined; function
473 object: user-defined function
475 A user-defined function object is created by a function definition (see
502 +-----------------------+-------------------------------+-----------+
508 +-----------------------+-------------------------------+-----------+
512 +-----------------------+-------------------------------+-----------+
513 | :attr:`__module__` | The name of the module the | Writable |
516 +-----------------------+-------------------------------+-----------+
522 +-----------------------+-------------------------------+-----------+
525 +-----------------------+-------------------------------+-----------+
526 | :attr:`__globals__` | A reference to the dictionary | Read-only |
528 | | global variables --- the | |
530 | | module in which the function | |
532 +-----------------------+-------------------------------+-----------+
536 +-----------------------+-------------------------------+-----------+
537 | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only |
540 +-----------------------+-------------------------------+-----------+
545 ``func_name`` is now writable.
548 The double-underscore attributes ``__closure__``, ``__code__``,
555 dot-notation is used to get and set such attributes. *Note that the current
556 implementation only supports function attributes on user-defined functions.
557 Function attributes on built-in functions may be supported in the future.*
562 User-defined methods
565 object: user-defined method
566 pair: user-defined; method
568 A user-defined method object combines a class, a class instance (or ``None``)
569 and any callable object (normally a user-defined function).
571 Special read-only attributes: :attr:`im_self` is the class instance object,
572 :attr:`im_func` is the function object; :attr:`im_class` is the class of
574 unbound methods; :attr:`__doc__` is the method's documentation (same as
575 ``im_func.__doc__``); :attr:`~definition.__name__` is the method name (same as
576 ``im_func.__name__``); :attr:`__module__` is the name of the module the method
583 For Python 3 forward-compatibility, :attr:`im_func` is also available as
596 User-defined method objects may be created when getting an attribute of a class
597 (perhaps via an instance of that class), if that attribute is a user-defined
598 function object, an unbound user-defined method object, or a class method
599 object. When the attribute is a user-defined method object, a new method object
600 is only created if the class from which it is being retrieved is the same as, or
602 the original method object is used as it is.
609 When a user-defined method object is created by retrieving a user-defined
610 function object from a class, its :attr:`im_self` attribute is ``None``
611 and the method object is said to be unbound. When one is created by
612 retrieving a user-defined function object from a class via one of its
613 instances, its :attr:`im_self` attribute is the instance, and the method
614 object is said to be bound. In either case, the new method's
615 :attr:`im_class` attribute is the class from which the retrieval takes
616 place, and its :attr:`im_func` attribute is the original function object.
620 When a user-defined method object is created by retrieving another method object
621 from a class or instance, the behaviour is the same as for a function object,
622 except that the :attr:`im_func` attribute of the new instance is not the
630 When a user-defined method object is created by retrieving a class method object
631 from a class or instance, its :attr:`im_self` attribute is the class itself, and
632 its :attr:`im_func` attribute is the function object underlying the class method.
634 When an unbound user-defined method object is called, the underlying function
635 (:attr:`im_func`) is called, with the restriction that the first argument must
639 When a bound user-defined method object is called, the underlying function
640 (:attr:`im_func`) is called, inserting the class instance (:attr:`im_self`) in
641 front of the argument list. For instance, when :class:`C` is a class which
642 contains a definition for a function :meth:`f`, and ``x`` is an instance of
643 :class:`C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.
645 When a user-defined method object is derived from a class method object, the
647 that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to calling ``f(C,1)``
648 where ``f`` is the underlying function.
651 object happens each time the attribute is retrieved from the class or instance.
652 In some cases, a fruitful optimization is to assign the attribute to a local
654 happens for user-defined functions; other callable objects (and all non-callable
655 objects) are retrieved without transformation. It is also important to note
656 that user-defined functions which are attributes of a class instance are not
657 converted to bound methods; this *only* happens when the function is an
666 :ref:`yield`) is called a :dfn:`generator
673 exception is raised and the iterator will have reached the end of the set of
676 Built-in functions
678 object: built-in function
682 A built-in function object is a wrapper around a C function. Examples of
683 built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
684 standard built-in module). The number and type of the arguments are
685 determined by the C function. Special read-only attributes:
686 :attr:`__doc__` is the function's documentation string, or ``None`` if
687 unavailable; :attr:`~definition.__name__` is the function's name; :attr:`__self__` is
688 set to ``None`` (but see the next item); :attr:`__module__` is the name of
689 the module the function was defined in or ``None`` if unavailable.
691 Built-in methods
693 object: built-in method
695 pair: built-in; method
697 This is really a different disguise of a built-in function, this time containing
699 a built-in method is ``alist.append()``, assuming *alist* is a list object. In
700 this case, the special read-only attribute :attr:`__self__` is set to the object
704 Class types, or "new-style classes," are callable. These objects normally act
718 Class objects are described below. When a class object is called, a new class
719 instance (also described below) is created and returned. This implies a call to
721 to the :meth:`__init__` method. If there is no :meth:`__init__` method, the
726 class has a :meth:`__call__` method; ``x(arguments)`` is a shorthand for
732 object: module
735 :ref:`import`). A module object has a
736 namespace implemented by a dictionary object (this is the dictionary referenced
737 by the func_globals attribute of functions defined in the module). Attribute
738 references are translated to lookups in this dictionary, e.g., ``m.x`` is
739 equivalent to ``m.__dict__["x"]``. A module object does not contain the code
740 object used to initialize the module (since it isn't needed once the
741 initialization is done).
743 Attribute assignment updates the module's namespace dictionary, e.g., ``m.x =
744 1`` is equivalent to ``m.__dict__["x"] = 1``.
746 .. index:: single: __dict__ (module attribute)
748 Special read-only attribute: :attr:`~object.__dict__` is the module's namespace as a
751 .. impl-detail::
753 Because of the way CPython clears module dictionaries, the module
754 dictionary will be cleared when the module falls out of scope even if the
756 or keep the module around while using its dictionary directly.
759 single: __name__ (module attribute)
760 single: __doc__ (module attribute)
761 single: __file__ (module attribute)
762 pair: module; namespace
764 Predefined (writable) attributes: :attr:`__name__` is the module's name;
765 :attr:`__doc__` is the module's documentation string, or ``None`` if
766 unavailable; :attr:`__file__` is the pathname of the file from which the module
767 was loaded, if it was loaded from a file. The :attr:`__file__` attribute is not
769 extension modules loaded dynamically from a shared library, it is the pathname
773 Both class types (new-style classes) and class objects (old-style/classic
777 ``C.x`` is translated to ``C.__dict__["x"]`` (although for new-style classes
779 locating attributes). When the attribute name is not found there, the
780 attribute search continues in the base classes. For old-style classes, the
781 search is depth-first, left-to-right in the order of occurrence in the base
782 class list. New-style classes use the more complex C3 method resolution
786 new-style classes can be found in the documentation accompanying the
801 user-defined function object or an unbound user-defined method object whose
802 associated class is either :class:`C` or one of its base classes, it is
803 transformed into an unbound user-defined method object whose :attr:`im_class`
804 attribute is :class:`C`. When it would yield a class method object, it is
805 transformed into a bound user-defined method object whose
806 :attr:`im_self` attribute is :class:`C`. When it would yield a
807 static method object, it is transformed into the object wrapped by the static
810 its :attr:`~object.__dict__` (note that only new-style classes support descriptors).
828 Special attributes: :attr:`~definition.__name__` is the class name; :attr:`__module__` is
829 the module name in which the class was defined; :attr:`~object.__dict__` is the
830 dictionary containing the class's namespace; :attr:`~class.__bases__` is a
832 order of their occurrence in the base class list; :attr:`__doc__` is the
842 A class instance is created by calling a class object (see above). A class
843 instance has a namespace implemented as a dictionary which is the first place in
844 which attribute references are searched. When an attribute is not found there,
846 with the class attributes. If a class attribute is found that is a user-defined
847 function object or an unbound user-defined method object whose associated class
848 is the class (call it :class:`C`) of the instance for which the attribute
849 reference was initiated or one of its bases, it is transformed into a bound
850 user-defined method object whose :attr:`im_class` attribute is :class:`C` and
851 whose :attr:`im_self` attribute is the instance. Static method and class method
856 class attribute is found, and the object's class has a :meth:`__getattr__`
857 method, that is called to satisfy the lookup.
863 :meth:`__delattr__` method, this is called instead of updating the instance
878 Special attributes: :attr:`~object.__dict__` is the attribute dictionary;
879 :attr:`~instance.__class__` is the instance's class.
884 builtin: open
885 single: popen() (in module os)
891 single: stdin (in module sys)
892 single: stdout (in module sys)
893 single: stderr (in module sys)
896 :func:`open` built-in function, and also by :func:`os.popen`,
901 error streams. See :ref:`bltin-file-objects` for complete documentation of
916 Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
917 The difference between a code object and a function object is that the function
918 object contains an explicit reference to the function's globals (the module in
921 (because they represent values calculated at run-time). Unlike function
941 Special read-only attributes: :attr:`co_name` gives the function name;
942 :attr:`co_argcount` is the number of positional arguments (including arguments
943 with default values); :attr:`co_nlocals` is the number of local variables used
944 by the function (including arguments); :attr:`co_varnames` is a tuple containing
946 :attr:`co_cellvars` is a tuple containing the names of local variables that are
947 referenced by nested functions; :attr:`co_freevars` is a tuple containing the
948 names of free variables; :attr:`co_code` is a string representing the sequence
949 of bytecode instructions; :attr:`co_consts` is a tuple containing the literals
950 used by the bytecode; :attr:`co_names` is a tuple containing the names used by
951 the bytecode; :attr:`co_filename` is the filename from which the code was
952 compiled; :attr:`co_firstlineno` is the first line number of the function;
953 :attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to
955 :attr:`co_stacksize` is the required stack size (including local variables);
956 :attr:`co_flags` is an integer encoding a number of flags for the interpreter.
960 The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is set if
962 positional arguments; bit ``0x08`` is set if the function uses the
963 ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set
964 if the function is a generator.
968 particular feature enabled: bit ``0x2000`` is set if the function was compiled
976 If a code object represents a function, the first item in :attr:`co_consts` is
979 .. _frame-objects:
996 Special read-only attributes: :attr:`f_back` is to the previous stack frame
997 (towards the caller), or ``None`` if this is the bottom stack frame;
998 :attr:`f_code` is the code object being executed in this frame; :attr:`f_locals`
999 is the dictionary used to look up local variables; :attr:`f_globals` is used for
1000 global variables; :attr:`f_builtins` is used for built-in (intrinsic) names;
1001 :attr:`f_restricted` is a flag indicating whether the function is executing in
1003 is an index into the bytecode string of the code object).
1012 Special writable attributes: :attr:`f_trace`, if not ``None``, is a function
1013 called at the start of each source code line (this is used by the debugger);
1017 is the current line number of the frame --- writing to this from within a trace
1018 function jumps to the given line (only for the bottom-most frame). A debugger
1027 single: exc_info (in module sys)
1028 single: exc_traceback (in module sys)
1029 single: last_traceback (in module sys)
1035 is created when an exception occurs. When the search for an exception handler
1036 unwinds the execution stack, at each unwound level a traceback object is
1037 inserted in front of the current traceback. When an exception handler is
1038 entered, the stack trace is made available to the program. (See section
1039 :ref:`try`.) It is accessible as ``sys.exc_traceback``,
1041 latter is the preferred interface, since it works correctly when the program is
1043 trace is written (nicely formatted) to the standard error stream; if the
1044 interpreter is interactive, it is also made available to the user as
1054 Special read-only attributes: :attr:`tb_next` is the next level in the stack
1055 trace (towards the frame where the exception occurred), or ``None`` if there is
1064 .. index:: builtin: slice
1066 Slice objects are used to represent slices when *extended slice syntax* is used.
1067 This is a slice using two colons, or multiple slices or ellipses separated by
1069 also created by the built-in :func:`slice` function.
1076 Special read-only attributes: :attr:`~slice.start` is the lower bound;
1077 :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step
1078 value; each is ``None`` if omitted. These attributes can have any type.
1089 slice. Missing or out-of-bounds indices are handled in a manner consistent with
1096 objects to method objects described above. A static method object is a wrapper
1097 around any other object, usually a user-defined method object. When a static
1098 method object is retrieved from a class or a class instance, the object actually
1099 returned is the wrapped object, which is not subject to any further
1101 objects they wrap usually are. Static method objects are created by the built-in
1105 A class method object, like a static method object, is a wrapper around another
1106 object that alters the way in which that object is retrieved from classes and
1107 class instances. The behaviour of class method objects upon such retrieval is
1108 described above, under "User-defined methods". Class method objects are created
1109 by the built-in :func:`classmethod` constructor.
1114 New-style and classic classes
1117 Classes and instances come in two flavors: old-style (or classic) and new-style.
1120 ``type``, and old-style classes were the only flavor available. For an
1121 old-style class, the statement ``x.__class__`` provides the class of *x*, but
1122 ``type(x)`` is always ``<type 'instance'>``. This reflects the fact that all
1123 old-style instances, independent of their class, are implemented with a single
1124 built-in type, called ``instance``.
1126 New-style classes were introduced in Python 2.2 to unify the concepts of
1127 ``class`` and ``type``. A new-style class is simply a user-defined type,
1128 no more, no less. If *x* is an instance of a new-style class, then ``type(x)``
1129 is typically the same as ``x.__class__`` (although this is not guaranteed -- a
1130 new-style class instance is permitted to override the value returned for
1133 The major motivation for introducing new-style classes is to provide a unified
1134 object model with a full meta-model. It also has a number of practical
1135 benefits, like the ability to subclass most built-in types, or the introduction
1138 For compatibility reasons, classes are still old-style by default. New-style
1139 classes are created by specifying another new-style class (i.e. a type) as a
1140 parent class, or the "top-level type" :class:`object` if no other parent is
1141 needed. The behaviour of new-style classes differs from that of old-style
1150 of new-style classes. Please see https://www.python.org/doc/newstyle/ for
1154 single: class; new-style
1156 single: class; old-style
1158 Old-style classes are removed in Python 3, leaving only new-style classes.
1172 with special names. This is Python's approach to :dfn:`operator overloading`,
1175 and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
1176 to ``x.__getitem__(i)`` for old-style classes and ``type(x).__getitem__(x, i)``
1177 for new-style classes. Except where mentioned, attempts to execute an
1178 operation raise an exception when no appropriate method is defined (typically
1181 When implementing a class that emulates any built-in type, it is important that
1185 of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document
1192 -------------------
1198 Called to create a new instance of class *cls*. :meth:`__new__` is a static
1199 method (special-cased so you need not declare it as such) that takes the class
1208 newly-created instance as necessary before returning it.
1212 *self* is the new instance and the remaining arguments are the same as were
1218 :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
1219 int, str, or tuple) to customize instance creation. It is also commonly
1228 it is returned to the caller. The arguments are those passed to the
1236 no non-``None`` value may be returned by :meth:`__init__`; doing so will
1246 Called when the instance is about to be destroyed. This is also called a
1249 deletion of the base class part of the instance. Note that it is possible
1252 later time when this new reference is deleted. It is not guaranteed that
1258 ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
1259 the reference count for ``x`` by one, and the latter is only called when
1262 circular references between objects (e.g., a doubly-linked list or a tree
1272 detected when the option cycle detector is enabled (it's on by default),
1273 but can only be cleaned up if there are no Python-level :meth:`__del__`
1274 methods involved. Refer to the documentation for the :mod:`gc` module for
1282 is printed to ``sys.stderr`` instead. Also, when :meth:`__del__` is invoked in
1283 response to a module being deleted (e.g., when execution of the program is
1290 deleted from their module before other globals are deleted; if no other
1292 modules are still available at the time when the :meth:`__del__` method is
1295 See also the :option:`-R` command-line option.
1300 .. index:: builtin: repr
1302 Called by the :func:`repr` built-in function and by string conversions (reverse
1306 this is not possible, a string of the form ``<...some useful description...>``
1308 defines :meth:`__repr__` but not :meth:`__str__`, then :meth:`__repr__` is also
1309 used when an "informal" string representation of instances of that class is
1316 single: back-quotes
1318 This is typically used for debugging, so it is important that the representation
1319 is information-rich and unambiguous.
1325 builtin: str
1328 Called by the :func:`str` built-in function and by the :keyword:`print`
1347 These are the so-called "rich comparison" methods, and are called for comparison
1349 operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
1357 methods can return any value, so if the comparison operator is used in a Boolean
1359 :func:`bool` on the value to determine if the result is true or false.
1362 of ``x==y`` does not imply that ``x!=y`` is false. Accordingly, when
1368 There are no swapped-argument versions of these methods (to be used when the
1382 builtin: cmp
1385 Called by comparison operations if rich comparison (see above) is not
1388 :meth:`__cmp__`, :meth:`__eq__` or :meth:`__ne__` operation is defined, class
1406 builtin: hash
1408 Called by built-in function :func:`hash` and for operations on members of
1411 property is that objects which compare equal have the same hash value; it is
1425 that an object's hash value is immutable (if the object's hash value changes,
1428 User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods
1434 value returned is no longer appropriate (e.g. by switching to a value-based
1445 :meth:`__hash__` may now also return a long integer object; the 32-bit
1446 integer is then derived from the hash of that object.
1457 Called to implement truth value testing and the built-in operation ``bool()``;
1459 ``1``. When this method is not defined, :meth:`__len__` is called, if it is
1460 defined, and the object is considered true if its result is nonzero.
1467 .. index:: builtin: unicode
1469 Called to implement :func:`unicode` built-in; should return a Unicode object.
1470 When this method is not defined, string conversion is attempted, and the result
1471 of string conversion is converted to Unicode using the system default encoding.
1474 .. _attribute-access:
1477 ----------------------------
1486 (i.e. it is not an instance attribute nor is it found in the class tree for
1487 ``self``). ``name`` is the attribute name. This method should return the
1492 Note that if the attribute is found through the normal mechanism,
1493 :meth:`__getattr__` is not called. (This is an intentional asymmetry between
1494 :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
1500 new-style classes.
1505 Called when an attribute assignment is attempted. This is called instead of the
1506 normal mechanism (i.e. store the value in the instance dictionary). *name* is
1507 the attribute name, *value* is the value to be assigned to it.
1512 simply execute ``self.name = value`` --- this would cause a recursive call to
1514 attributes, e.g., ``self.__dict__[name] = value``. For new-style classes,
1523 should only be implemented if ``del obj.name`` is meaningful for the object.
1526 .. _new-style-attribute-access:
1528 More attribute access for new-style classes
1531 The following methods only apply to new-style classes.
1548 result of implicit invocation via language syntax or built-in functions.
1549 See :ref:`new-style-special-lookup`.
1558 method (a so-called *descriptor* class) appears in an *owner* class (the
1561 refers to the attribute whose name is the key of the property in the owner
1568 instance of that class (instance attribute access). *owner* is always the owner
1569 class, while *instance* is the instance that the attribute was accessed through,
1570 or ``None`` when the attribute is accessed through the *owner*. This method
1586 .. _descriptor-invocation:
1591 In general, a descriptor is an object attribute with "binding behavior", one
1594 those methods are defined for an object, it is said to be a descriptor.
1596 The default behavior for attribute access is to get, set, or delete the
1601 However, if the looked-up value is an object defining one of the descriptor
1608 The starting point for descriptor invocation is a binding, ``a.x``. How the
1612 The simplest and least common call is when user code directly invokes a
1616 If binding to a new-style object instance, ``a.x`` is transformed into the call:
1620 If binding to a new-style class, ``A.x`` is transformed into the call:
1624 If ``a`` is an instance of :class:`super`, then the binding ``super(B,
1633 object itself unless there is a value in the object's instance dictionary. If
1634 the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data
1635 descriptor; if it defines neither, it is a non-data descriptor. Normally, data
1636 descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data
1639 instance dictionary. In contrast, non-data descriptors can be overridden by
1643 implemented as non-data descriptors. Accordingly, instances can redefine and
1647 The :func:`property` function is implemented as a data descriptor. Accordingly,
1656 By default, instances of both old and new-style classes have a dictionary for
1661 The default can be overridden by defining *__slots__* in a new-style class
1664 variable. Space is saved because *__dict__* is not created for each instance.
1670 with variable names used by instances. If defined in a new-style class,
1680 subclass is meaningless.
1685 variables is desired, then add ``'__dict__'`` to the sequence of strings in the
1695 support is needed, then add ``'__weakref__'`` to the sequence of strings in the
1708 * The action of a *__slots__* declaration is limited to the class where it is
1713 defined by the base class slot is inaccessible (except by retrieving its
1717 * Nonempty *__slots__* does not work for classes derived from "variable-length"
1718 built-in types such as :class:`long`, :class:`str` and :class:`tuple`.
1720 * Any non-string iterable may be assigned to *__slots__*. Mappings may also be
1734 --------------------------
1736 By default, new-style classes are constructed using :func:`type`. A class
1737 definition is read into a separate namespace and the value of class name is
1740 When the class definition is read, if *__metaclass__* is defined then the
1747 * Returning an instance of another class -- essentially performing the role of a
1751 -- :meth:`type.__new__` can then be called from this method to create a class
1762 behavior when the class is called, e.g. not always creating a new instance.
1768 and ``dict``. Upon class creation, the callable is used instead of the built-in
1773 The appropriate metaclass is determined by the following precedence rules:
1775 * If ``dict['__metaclass__']`` exists, it is used.
1777 * Otherwise, if there is at least one base class, its metaclass is used (this
1780 * Otherwise, if a global variable named __metaclass__ exists, it is used.
1782 * Otherwise, the old-style, classic metaclass (types.ClassType) is used.
1791 ----------------------------------------
1796 :func:`isinstance` and :func:`issubclass` built-in functions.
1800 classes" to any class or type (including built-in types), including other
1818 cannot be defined as class methods in the actual class. This is consistent with
1820 case the instance is itself a class.
1824 :pep:`3119` - Introducing Abstract Base Classes
1829 module) to the language.
1832 .. _callable-types:
1835 --------------------------
1842 Called when the instance is "called" as a function; if this method is defined,
1843 ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``.
1846 .. _sequence-types:
1849 -------------------------
1853 but can represent other containers as well. The first set of methods is used
1854 either to emulate a sequence or to emulate a mapping; the difference is that for
1856 N`` where *N* is the length of the sequence, or slice objects, which define a
1859 is also recommended that mappings provide the methods :meth:`keys`,
1863 to those for Python's standard dictionary objects. The :mod:`UserDict` module
1873 :meth:`__coerce__` or other numerical operators. It is recommended that both
1876 of :meth:`has_key`; for sequences, it should search through the values. It is
1886 builtin: len
1889 Called to implement the built-in function :func:`len`. Should return the length
1891 :meth:`__nonzero__` method and whose :meth:`__len__` method returns zero is
1894 .. impl-detail::
1896 In CPython, the length is required to be at most :attr:`sys.maxsize`.
1897 If the length is larger than :attr:`!sys.maxsize` some features (such as
1910 type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate
1913 :exc:`IndexError` should be raised. For mapping types, if *key* is missing (not
1925 when key is not in the dictionary.
1948 This method is called when an iterator is required for a container. This method
1959 Called (if present) by the :func:`reversed` built-in to implement
1963 If the :meth:`__reversed__` method is not provided, the :func:`reversed`
1964 built-in will fall back to using the sequence protocol (:meth:`__len__` and
1967 that is more efficient than the one provided by :func:`reversed`.
1980 is in *self*, false otherwise. For mapping objects, this should consider the
1981 keys of the mapping rather than the values or the key-item pairs.
1986 reference <membership-test-details>`.
1989 .. _sequence-methods:
1992 --------------------------------------------------
2003 (However, built-in types in CPython currently still implement
2010 negative indexes are used in the slice, the length of the sequence is added
2012 an :exc:`AttributeError` is raised. No guarantee is made that indexes
2014 length of the sequence are not modified. If no :meth:`__getslice__` is found,
2015 a slice object is created instead, and passed to :meth:`__getitem__` instead.
2023 This method is deprecated. If no :meth:`__setslice__` is found, or for extended
2024 slicing of the form ``self[i:j:k]``, a slice object is created, and passed to
2031 :meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
2032 found, or for extended slicing of the form ``self[i:j:k]``, a slice object is
2037 colon is used, and the slice method is available. For slice operations
2039 :meth:`__getitem__`, :meth:`__setitem__` or :meth:`__delitem__` is called with a
2042 The following example demonstrate how to make your program or module compatible
2057 # They won't be defined if version is at least 2.0 final
2071 values. For each negative index value, the length of the sequence is added to
2073 index); this is the customary handling of negative indexes by the built-in
2081 .. _numeric-types:
2084 -----------------------
2088 number implemented (e.g., bitwise operations for non-integral numbers) should be
2106 builtin: divmod
2107 builtin: pow
2108 builtin: pow
2111 ``-``, ``*``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``,
2113 ``x + y``, where *x* is an instance of a class that has an :meth:`__add__`
2114 method, ``x.__add__(y)`` is called. The :meth:`__divmod__` method should be the
2118 the built-in :func:`pow` function is to be supported.
2127 The division operator (``/``) is implemented by these methods. The
2128 :meth:`__truediv__` method is used when ``__future__.division`` is in effect,
2129 otherwise :meth:`__div__` is used. If only one of these two methods is defined,
2150 builtin: divmod
2151 builtin: pow
2154 ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``,
2158 expression ``x - y``, where *y* is an instance of a class that has an
2159 :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns
2162 .. index:: builtin: pow
2169 If the right operand's type is a subclass of the left operand's type and that
2171 called before the left operand's non-reflected method. This behavior allows
2190 (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
2192 in-place (modifying *self*) and return the result (which could be, but does
2193 not have to be, *self*). If a specific method is not defined, the augmented
2195 statement ``x += y``, where *x* is an instance of a class that has an
2196 :meth:`__iadd__` method, ``x.__iadd__(y)`` is called. If *x* is an instance
2206 .. index:: builtin: abs
2208 Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
2218 builtin: complex
2219 builtin: int
2220 builtin: long
2221 builtin: float
2223 Called to implement the built-in functions :func:`complex`, :func:`int`,
2231 builtin: oct
2232 builtin: hex
2234 Called to implement the built-in functions :func:`oct` and :func:`hex`. Should
2248 Called to implement "mixed-mode" numeric arithmetic. Should either return a
2249 2-tuple containing *self* and *other* converted to a common numeric type, or
2250 ``None`` if conversion is impossible. When the common type would be the type of
2251 ``other``, it is sufficient to return ``None``, since the interpreter will also
2253 of the other type cannot be changed, it is useful to do the conversion to the
2254 other type here). A return value of ``NotImplemented`` is equivalent to
2258 .. _coercion-rules:
2261 --------------
2265 what one version of one particular implementation does is undesirable. Instead,
2271 If the left operand of a % operator is a string or Unicode object, no coercion
2272 takes place and the string formatting operation is invoked instead.
2276 It is no longer recommended to define a coercion operation. Mixed-mode
2282 New-style classes (those derived from :class:`object`) never invoke the
2284 :meth:`__coerce__` is invoked is when the built-in function :func:`coerce` is
2289 For most intents and purposes, an operator that returns ``NotImplemented`` is
2290 treated the same as one that is not implemented at all.
2295 names corresponding to an operator; :meth:`__iop__` is used for the
2296 corresponding in-place operator. For example, for the operator '``+``',
2298 the binary operator, and :meth:`__iadd__` for the in-place variant.
2302 For objects *x* and *y*, first ``x.__op__(y)`` is tried. If this is not
2303 implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is tried. If this
2304 is also not implemented or returns ``NotImplemented``, a :exc:`TypeError`
2305 exception is raised. But see the following exception:
2309 Exception to the previous item: if the left operand is an instance of a built-in
2310 type or a new-style class, and the right operand is an instance of a proper
2312 the right operand's :meth:`__rop__` method is tried *before* the left operand's
2315 This is done so that a subclass can completely override binary operators.
2317 right operand: when an instance of a given class is expected, an instance of a
2318 subclass of that class is always acceptable.
2322 When either operand type defines a coercion, this coercion is called before that
2323 type's :meth:`__op__` or :meth:`__rop__` method is called, but no sooner. If
2325 coercion is invoked, part of the process is redone using the new object.
2329 When an in-place operator (like '``+=``') is used, if the left operand
2330 implements :meth:`__iop__`, it is invoked without any coercion. When the
2336 In ``x + y``, if *x* is a sequence that implements sequence concatenation,
2337 sequence concatenation is invoked.
2341 In ``x * y``, if one operand is a sequence that implements sequence
2342 repetition, and the other is an integer (:class:`int` or :class:`long`),
2343 sequence repetition is invoked.
2348 coercion. Three-way comparison (implemented by :meth:`__cmp__`) does use
2353 In the current implementation, the built-in numeric types :class:`int`,
2355 All these types implement a :meth:`__coerce__` method, for use by the built-in
2361 method for mixed-type binary arithmetic operations.
2364 .. _context-managers:
2367 -------------------------------
2371 A :dfn:`context manager` is an object that defines the runtime context to be
2401 If an exception is supplied, and the method wishes to suppress the exception
2405 Note that :meth:`__exit__` methods should not reraise the passed-in exception;
2406 this is the caller's responsibility.
2411 :pep:`343` - The "with" statement
2416 .. _old-style-special-lookup:
2418 Special method lookup for old-style classes
2419 -------------------------------------------
2421 For old-style classes, special methods are always looked up in exactly the
2422 same way as any other method or attribute. This is the case regardless of
2423 whether the method is being looked up explicitly as in ``x.__getitem__(i)``
2427 for different instances of a single old-style class if the appropriate
2443 .. _new-style-special-lookup:
2445 Special method lookup for new-style classes
2446 -------------------------------------------
2448 For new-style classes, implicit invocations of special methods are only guaranteed
2450 dictionary. That behaviour is the reason why the following code raises an
2451 exception (unlike the equivalent example with old-style classes)::
2460 File "<stdin>", line 1, in <module>
2473 File "<stdin>", line 1, in <module>
2476 Incorrectly attempting to invoke an unbound method of a class in this way is
2477 sometimes referred to as 'metaclass confusion', and is avoided by bypassing
2521 .. [#] It *is* possible in some cases to change an object's type, under certain
2523 lead to some very strange behaviour if it is handled incorrectly.
2525 .. [#] For operands of the same type, it is assumed that if the non-reflected method
2526 (such as :meth:`__add__`) fails the operation is not supported, which is why the
2527 reflected method is not called.