PageRenderTime 67ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/reference/datamodel.rst

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