Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3a5d7e3

Browse files
committed
Merged revisions 65487 (with heavy modifications for Py3k as well as some cleanups of the type heirarchy) via svnmerge from
svn+ssh://[email protected]/python/trunk ........ r65487 | nick.coghlan | 2008-08-04 22:40:59 +1000 (Mon, 04 Aug 2008) | 1 line Issue 643841: better documentation of the special method lookup process, especially for new-style classes. Also removes the warnings about not being authoritative for new-style classes - the language reference actually covers those fairly well now (albeit in a fashion that isn't always particularly easy to follow). ........
1 parent 0d85539 commit 3a5d7e3

1 file changed

Lines changed: 137 additions & 52 deletions

File tree

Doc/reference/datamodel.rst

Lines changed: 137 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Every object has an identity, a type and a value. An object's *identity* never
3636
changes once it has been created; you may think of it as the object's address in
3737
memory. The ':keyword:`is`' operator compares the identity of two objects; the
3838
:func:`id` function returns an integer representing its identity (currently
39-
implemented as its address). An object's :dfn:`type` is also unchangeable.
39+
implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
4040
An object's type determines the operations that the object supports (e.g., "does
4141
it have a length?") and also defines the possible values for objects of that
4242
type. The :func:`type` function returns an object's type (which is an object
@@ -77,7 +77,7 @@ garbage-collected, but since garbage collection is not guaranteed to happen,
7777
such objects also provide an explicit way to release the external resource,
7878
usually a :meth:`close` method. Programs are strongly recommended to explicitly
7979
close such objects. The ':keyword:`try`...\ :keyword:`finally`' statement
80-
provides a convenient way to do this.
80+
and the ':keyword:`with`' statement provide convenient ways to do this.
8181

8282
.. index:: single: container
8383

@@ -116,7 +116,8 @@ The standard type hierarchy
116116
Below is a list of the types that are built into Python. Extension modules
117117
(written in C, Java, or other languages, depending on the implementation) can
118118
define additional types. Future versions of Python may add types to the type
119-
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).
119+
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
120+
although such additions will often be provided via the standard library instead.
120121

121122
.. index::
122123
single: attribute
@@ -172,15 +173,15 @@ Ellipsis
172173

173174
There are two types of integers:
174175

175-
Integers
176+
Integers (:class:`int`)
176177

177178
These represent numbers in an unlimited range, subject to available (virtual)
178179
memory only. For the purpose of shift and mask operations, a binary
179180
representation is assumed, and negative numbers are represented in a variant of
180181
2's complement which gives the illusion of an infinite string of sign bits
181182
extending to the left.
182183

183-
Booleans
184+
Booleans (:class:`bool`)
184185
.. index::
185186
object: Boolean
186187
single: False
@@ -212,7 +213,7 @@ Ellipsis
212213
overhead of using objects in Python, so there is no reason to complicate the
213214
language with two kinds of floating point numbers.
214215

215-
:class:`numbers.Complex`
216+
:class:`numbers.Complex` (:class:`complex`)
216217
.. index::
217218
object: complex
218219
pair: complex; number
@@ -293,6 +294,15 @@ Sequences
293294
parentheses must be usable for grouping of expressions). An empty
294295
tuple can be formed by an empty pair of parentheses.
295296

297+
Bytes
298+
.. index:: bytes, byte
299+
300+
A bytes object is an immutable array. The items are 8-bit bytes,
301+
represented by integers in the range 0 <= x < 256. Bytes literals
302+
(like ``b'abc'`` and the built-in function :func:`bytes` can be used to
303+
construct bytes objects. Also, bytes objects can be decoded to strings
304+
via the :meth:`decode` method.
305+
296306
Mutable sequences
297307
.. index::
298308
object: mutable sequence
@@ -316,19 +326,18 @@ Sequences
316326
placing a comma-separated list of expressions in square brackets. (Note
317327
that there are no special cases needed to form lists of length 0 or 1.)
318328

319-
Bytes
320-
.. index:: bytes, byte
329+
Byte Arrays
330+
.. index:: bytearray
321331

322-
A bytes object is a mutable array. The items are 8-bit bytes,
323-
represented by integers in the range 0 <= x < 256. Bytes literals
324-
(like ``b'abc'`` and the built-in function :func:`bytes` can be used to
325-
construct bytes objects. Also, bytes objects can be decoded to strings
326-
via the :meth:`decode` method.
332+
A bytearray object is a mutable array. They are created by the built-in
333+
:func:`bytearray` constructor. Aside from being mutable (and hence
334+
unhashable), byte arrays otherwise provide the same interface and
335+
functionality as immutable bytes objects.
327336

328337
.. index:: module: array
329338

330339
The extension module :mod:`array` provides an additional example of a
331-
mutable sequence type.
340+
mutable sequence type, as does the :mod:`collections` module.
332341

333342
Set types
334343
.. index::
@@ -399,7 +408,8 @@ Mappings
399408
module: bsddb
400409

401410
The extension modules :mod:`dbm.ndbm`, :mod:`dbm.gnu`, and :mod:`bsddb`
402-
provide additional examples of mapping types.
411+
provide additional examples of mapping types, as does the :mod:`collections`
412+
module.
403413

404414
Callable types
405415
.. index::
@@ -524,7 +534,7 @@ Callable types
524534
User-defined method objects may be created when getting an attribute of a
525535
class (perhaps via an instance of that class), if that attribute is a
526536
user-defined function object or a class method object.
527-
537+
528538
When an instance method object is created by retrieving a user-defined
529539
function object from a class via one of its instances, its
530540
:attr:`__self__` attribute is the instance, and the method object is said
@@ -571,11 +581,11 @@ Callable types
571581
single: generator; iterator
572582

573583
A function or method which uses the :keyword:`yield` statement (see section
574-
:ref:`yield`) is called a :dfn:`generator
575-
function`. Such a function, when called, always returns an iterator object
576-
which can be used to execute the body of the function: calling the iterator's
577-
:meth:`__next__` method will cause the function to execute until it provides a
578-
value using the :keyword:`yield` statement. When the function executes a
584+
:ref:`yield`) is called a :dfn:`generator function`. Such a function, when
585+
called, always returns an iterator object which can be used to execute the
586+
body of the function: calling the iterator's :meth:`__next__` method will
587+
cause the function to execute until it provides a value using the
588+
:keyword:`yield` statement. When the function executes a
579589
:keyword:`return` statement or falls off the end, a :exc:`StopIteration`
580590
exception is raised and the iterator will have reached the end of the set of
581591
values to be returned.
@@ -655,18 +665,21 @@ Modules
655665
extension modules loaded dynamically from a shared library, it is the pathname
656666
of the shared library file.
657667

658-
.. XXX "Classes" and "Instances" is outdated!
659-
see http://www.python.org/doc/newstyle.html for newstyle information
660-
661668
Custom classes
662-
Class objects are created by class definitions (see section :ref:`class`). A
663-
class has a namespace implemented by a dictionary object. Class attribute
664-
references are translated to lookups in this dictionary, e.g., ``C.x`` is
665-
translated to ``C.__dict__["x"]``. When the attribute name is not found
666-
there, the attribute search continues in the base classes. The search is
667-
depth-first, left-to-right in the order of occurrence in the base class list.
668-
669-
.. XXX document descriptors and new MRO
669+
Custon class types are typically created by class definitions (see section
670+
:ref:`class`). A class has a namespace implemented by a dictionary object.
671+
Class attribute references are translated to lookups in this dictionary, e.g.,
672+
``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of
673+
hooks which allow for other means of locating attributes). When the attribute
674+
name is not found there, the attribute search continues in the base classes.
675+
This search of the base classes uses the C3 method resolution order which
676+
behaves correctly even in the presence of 'diamond' inheritance structures
677+
where there are multiple inheritance paths leading back to a common ancestor.
678+
Additional details on the C3 MRO used by Python can be found in the
679+
documentation accompanying the 2.3 release at
680+
http://www.python.org/download/releases/2.3/mro/.
681+
682+
.. XXX: Could we add that MRO doc as an appendix to the language ref?
670683
671684
.. index::
672685
object: class
@@ -980,25 +993,10 @@ A class can implement certain operations that are invoked by special syntax
980993
with special names. This is Python's approach to :dfn:`operator overloading`,
981994
allowing classes to define their own behavior with respect to language
982995
operators. For instance, if a class defines a method named :meth:`__getitem__`,
983-
and ``x`` is an instance of this class, then ``x[i]`` is equivalent to
984-
``x.__getitem__(i)``. Except where mentioned, attempts to execute an operation
985-
raise an exception when no appropriate method is defined.
986-
987-
.. XXX above translation is not correct for new-style classes!
988-
989-
Special methods are only guaranteed to work if defined in an object's class, not
990-
in the object's instance dictionary. That explains why this won't work::
991-
992-
>>> class C:
993-
... pass
994-
...
995-
>>> c = C()
996-
>>> c.__len__ = lambda: 5
997-
>>> len(c)
998-
Traceback (most recent call last):
999-
File "<stdin>", line 1, in <module>
1000-
TypeError: object of type 'C' has no len()
1001-
996+
and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
997+
to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an
998+
operation raise an exception when no appropriate method is defined (typically
999+
:exc:`AttributeError` or :exc:`TypeError`).
10021000

10031001
When implementing a class that emulates any built-in type, it is important that
10041002
the emulation only be implemented to the degree that it makes sense for the
@@ -1277,7 +1275,7 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
12771275
Note that if the attribute is found through the normal mechanism,
12781276
:meth:`__getattr__` is not called. (This is an intentional asymmetry between
12791277
:meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
1280-
reasons and because otherwise :meth:`__setattr__` would have no way to access
1278+
reasons and because otherwise :meth:`__getattr__` would have no way to access
12811279
other attributes of the instance. Note that at least for instance variables,
12821280
you can fake total control by not inserting any values in the instance attribute
12831281
dictionary (but instead inserting them in another object). See the
@@ -1296,6 +1294,12 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
12961294
method with the same name to access any attributes it needs, for example,
12971295
``object.__getattribute__(self, name)``.
12981296

1297+
.. note::
1298+
1299+
This method may still be bypassed when looking up special methods as the
1300+
result of implicit invocation via language syntax or builtin functions.
1301+
See :ref:`special-lookup`.
1302+
12991303

13001304
.. method:: object.__setattr__(self, name, value)
13011305

@@ -1881,8 +1885,89 @@ For more information on context managers, see :ref:`typecontextmanager`.
18811885
The specification, background, and examples for the Python :keyword:`with`
18821886
statement.
18831887

1888+
1889+
.. _special-lookup:
1890+
1891+
Special method lookup
1892+
---------------------
1893+
1894+
For custom classes, implicit invocations of special methods are only guaranteed
1895+
to work correctly if defined on an object's type, not in the object's instance
1896+
dictionary. That behaviour is the reason why the following code raises an
1897+
exception::
1898+
1899+
>>> class C(object):
1900+
... pass
1901+
...
1902+
>>> c = C()
1903+
>>> c.__len__ = lambda: 5
1904+
>>> len(c)
1905+
Traceback (most recent call last):
1906+
File "<stdin>", line 1, in <module>
1907+
TypeError: object of type 'C' has no len()
1908+
1909+
The rationale behind this behaviour lies with a number of special methods such
1910+
as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects,
1911+
including type objects. If the implicit lookup of these methods used the
1912+
conventional lookup process, they would fail when invoked on the type object
1913+
itself::
1914+
1915+
>>> 1 .__hash__() == hash(1)
1916+
True
1917+
>>> int.__hash__() == hash(int)
1918+
Traceback (most recent call last):
1919+
File "<stdin>", line 1, in <module>
1920+
TypeError: descriptor '__hash__' of 'int' object needs an argument
1921+
1922+
Incorrectly attempting to invoke an unbound method of a class in this way is
1923+
sometimes referred to as 'metaclass confusion', and is avoided by bypassing
1924+
the instance when looking up special methods::
1925+
1926+
>>> type(1).__hash__(1) == hash(1)
1927+
True
1928+
>>> type(int).__hash__(int) == hash(int)
1929+
True
1930+
1931+
In addition to bypassing any instance attributes in the interest of
1932+
correctness, implicit special method lookup may also bypass the
1933+
:meth:`__getattribute__` method even of the object's metaclass::
1934+
1935+
>>> class Meta(type):
1936+
... def __getattribute__(*args):
1937+
... print "Metaclass getattribute invoked"
1938+
... return type.__getattribute__(*args)
1939+
...
1940+
>>> class C(object):
1941+
... __metaclass__ = Meta
1942+
... def __len__(self):
1943+
... return 10
1944+
... def __getattribute__(*args):
1945+
... print "Class getattribute invoked"
1946+
... return object.__getattribute__(*args)
1947+
...
1948+
>>> c = C()
1949+
>>> c.__len__() # Explicit lookup via instance
1950+
Class getattribute invoked
1951+
10
1952+
>>> type(c).__len__(c) # Explicit lookup via type
1953+
Metaclass getattribute invoked
1954+
10
1955+
>>> len(c) # Implicit lookup
1956+
10
1957+
1958+
Bypassing the :meth:`__getattribute__` machinery in this fashion
1959+
provides significant scope for speed optimisations within the
1960+
interpreter, at the cost of some flexibility in the handling of
1961+
special methods (the special method *must* be set on the class
1962+
object itself in order to be consistently invoked by the interpreter).
1963+
1964+
18841965
.. rubric:: Footnotes
18851966

1967+
.. [#] It *is* possible in some cases to change an object's type, under certain
1968+
controlled conditions. It generally isn't a good idea though, since it can
1969+
lead to some very strange behaviour if it is handled incorrectly.
1970+
18861971
.. [#] A descriptor can define any combination of :meth:`__get__`,
18871972
:meth:`__set__` and :meth:`__delete__`. If it does not define :meth:`__get__`,
18881973
then accessing the attribute even on an instance will return the descriptor

0 commit comments

Comments
 (0)