# HG changeset patch # Parent 89d34aea8d7ef511819cfa50bc2d2f33a1fb7352 diff -r 89d34aea8d7e Doc/library/functions.rst --- a/Doc/library/functions.rst Thu Jul 30 10:14:52 2015 +0200 +++ b/Doc/library/functions.rst Thu Jul 30 12:40:08 2015 +0000 @@ -849,14 +849,16 @@ .. class:: object() - Return a new featureless object. :class:`object` is a base for all classes. - It has the methods that are common to all instances of Python classes. This - function does not accept any arguments. + This is the ultimate base class of all other classes. + It has methods that are common to all instances of Python classes. + When the constructor is called, it returns a new featureless object. + The constructor does not accept any arguments. .. note:: - :class:`object` does *not* have a :attr:`~object.__dict__`, so you can't - assign arbitrary attributes to an instance of the :class:`object` class. + The :class:`object` class does *not* have a :attr:`~object.__dict__`, + so you can't assign arbitrary attributes to a direct instance of + the :class:`object` class. .. function:: oct(x) diff -r 89d34aea8d7e Doc/library/stdtypes.rst --- a/Doc/library/stdtypes.rst Thu Jul 30 10:14:52 2015 +0200 +++ b/Doc/library/stdtypes.rst Thu Jul 30 12:40:08 2015 +0000 @@ -4322,7 +4322,8 @@ Other Built-in Types ==================== -The interpreter supports several other kinds of objects. Most of these support +The interpreter supports several other kinds of objects, as well as direct +instances of :class:`object`, the universal type. Most of these support only one or two operations. diff -r 89d34aea8d7e Doc/reference/datamodel.rst --- a/Doc/reference/datamodel.rst Thu Jul 30 10:14:52 2015 +0200 +++ b/Doc/reference/datamodel.rst Thu Jul 30 12:40:08 2015 +0000 @@ -126,7 +126,9 @@ pair: extension; module pair: C; language -Below is a list of the types that are built into Python. Extension modules +Below is a list of the types that are built into Python. +The fundamental type is :class:`object`; all other types, +whether built-in or not, are derived from it. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), @@ -1088,10 +1090,12 @@ class). The return value of :meth:`__new__` should be the new object instance (usually an instance of *cls*). - Typical implementations create a new instance of the class by invoking the + Typical custom implementations create a new instance of the class by invoking the superclass's :meth:`__new__` method using ``super(currentclass, - cls).__new__(cls[, ...])`` with appropriate arguments and then modifying the - newly-created instance as necessary before returning it. + cls).__new__(cls[, ...])`` with appropriate arguments and then modify the + newly-created instance as necessary before returning it. The base + implementation in :class:`object` should only be passed the *cls* + argument, and returns an uninitialized instance of that class. If :meth:`__new__` returns an instance of *cls*, then the new instance's :meth:`__init__` method will be invoked like ``__init__(self[, ...])``, where @@ -1113,9 +1117,14 @@ Called after the instance has been created (by :meth:`__new__`), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an :meth:`__init__` - method, the derived class's :meth:`__init__` method, if any, must explicitly + method, the derived class's :meth:`__init__` method, if any, may need to call it to ensure proper initialization of the base class part of the instance; for example: ``BaseClass.__init__(self, [args...])``. + Any :meth:`__init__` method that is overridden is not implicitly called. + + A base implementation in :class:`object` is provided, but it does not + need to be called. If it is only passed the *self* argument, it has + no effect. Because :meth:`__new__` and :meth:`__init__` work together in constructing objects (:meth:`__new__` to create it, and :meth:`__init__` to customise it), @@ -1132,7 +1141,9 @@ Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a :meth:`__del__` method, the derived class's :meth:`__del__` method, if any, must explicitly call it to ensure proper - deletion of the base class part of the instance. Note that it is possible + deletion of the base class part of the instance. + The :class:`object` class itself does not have a + :meth:`__del__` method. Note that it is possible (though not recommended!) for the :meth:`__del__` method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that @@ -1194,7 +1205,8 @@ "informal" string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation - is information-rich and unambiguous. + is information-rich and unambiguous. A default implementation is + provided by the :class:`object` class itself. .. index:: single: string; __str__() (object method) @@ -1204,8 +1216,9 @@ .. method:: object.__str__(self) - Called by :func:`str(object) ` and the built-in functions - :func:`format` and :func:`print` to compute the "informal" or nicely + Called by :func:`str(object) `, the default + :meth:`__format__` implementation, and the built-in function + :func:`print`, to compute the "informal" or nicely printable string representation of an object. The return value must be a :ref:`string ` object. @@ -1224,7 +1237,8 @@ .. index:: builtin: bytes Called by :func:`bytes` to compute a byte-string representation of an - object. This should return a ``bytes`` object. + object. This should return a ``bytes`` object. The :class:`object` + class itself does not provide this method. .. index:: single: string; __format__() (object method) @@ -1247,6 +1261,9 @@ The return value must be a string object. + The default implementation by the ``object`` class should be given + an empty ``format_spec`` string. It delegates to :meth:`__str__`. + .. versionchanged:: 3.4 The __format__ method of ``object`` itself raises a :exc:`TypeError` if passed any non-empty string. @@ -1294,6 +1311,12 @@ To automatically generate ordering operations from a single root operation, see :func:`functools.total_ordering`. + By default, the :class:`object` class provides implementations + consistent with :ref:`comparisons`: equality compares according to + object identity, and order comparisons raise :exc:`TypeError`. + Each default method may generate these results directly, but may + also return ``NotImplemented``. + .. method:: object.__hash__(self) .. index:: @@ -1327,7 +1350,8 @@ immutable (if the object's hash value changes, it will be in the wrong hash bucket). - User-defined classes have :meth:`__eq__` and :meth:`__hash__` methods + User-defined classes (and the :class:`object` class itself) + have :meth:`__eq__` and :meth:`__hash__` methods by default; with them, all objects compare unequal (except with themselves) and ``x.__hash__()`` returns an appropriate value such that ``x == y`` implies both that ``x is y`` and ``hash(x) == hash(y)``. @@ -1380,8 +1404,8 @@ ``bool()``; should return ``False`` or ``True``. When this method is not defined, :meth:`__len__` is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither - :meth:`__len__` nor :meth:`__bool__`, all its instances are considered - true. + :meth:`__len__` nor :meth:`__bool__` (which is true of the + :class:`object` class itself), all its instances are considered true. .. _attribute-access: @@ -1401,6 +1425,7 @@ (i.e. it is not an instance attribute nor is it found in the class tree for ``self``). ``name`` is the attribute name. This method should return the (computed) attribute value or raise an :exc:`AttributeError` exception. + The :class:`object` class itself does not provide this method. Note that if the attribute is found through the normal mechanism, :meth:`__getattr__` is not called. (This is an intentional asymmetry between @@ -1451,7 +1476,10 @@ .. method:: object.__dir__(self) Called when :func:`dir` is called on the object. A sequence must be - returned. :func:`dir` converts the returned sequence to a list and sorts it. + returned. The :func:`dir` function converts the returned sequence to + a list and sorts it. The :class:`object` class itself provides an + implementation consistent with the :func:`dir` behaviour for + arbitrary objects. .. _descriptors: @@ -1464,7 +1492,8 @@ descriptor must be in either the owner's class dictionary or in the class dictionary for one of its parents). In the examples below, "the attribute" refers to the attribute whose name is the key of the property in the owner -class' :attr:`__dict__`. +class' :attr:`__dict__`. The :class:`object` class itself does not +implement any of these protocols. .. method:: object.__get__(self, instance, owner) @@ -1564,7 +1593,8 @@ __slots__ ^^^^^^^^^ -By default, instances of classes have a dictionary for attribute storage. This +By default, instances of user-defined classes +have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances. @@ -1829,6 +1859,7 @@ Called when the instance is "called" as a function; if this method is defined, ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``. + The :class:`object` class itself does not provide this method. .. _sequence-types: @@ -1836,7 +1867,10 @@ Emulating container types ------------------------- -The following methods can be defined to implement container objects. Containers +The following methods can be defined to implement container objects. +None of them are provided by the :class:`object` class itself. + +Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for @@ -2160,6 +2194,9 @@ For more information on context managers, see :ref:`typecontextmanager`. +The :class:`object` class itself does not provide the +context manager methods. + .. method:: object.__enter__(self) @@ -2290,6 +2327,9 @@ :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements this method to be compatible with the :keyword:`await` expression. + The :class:`object` class itself is not awaitable and does not provide + this method. + .. versionadded:: 3.5 .. seealso:: :pep:`492` for additional information about awaitable objects. @@ -2356,6 +2396,8 @@ Asynchronous iterators can be used in a :keyword:`async for` statement. +The :class:`object` class itself does not provide these methods. + .. method:: object.__aiter__(self) Must return an *awaitable* resulting in an *asynchronous iterator* object. @@ -2391,6 +2433,8 @@ Asynchronous context managers can be used in a :keyword:`async with` statement. +The :class:`object` class itself does not provide these methods. + .. method:: object.__aenter__(self) This method is semantically similar to the :meth:`__enter__`, with only diff -r 89d34aea8d7e Lib/test/test_class.py --- a/Lib/test/test_class.py Thu Jul 30 10:14:52 2015 +0200 +++ b/Lib/test/test_class.py Thu Jul 30 12:40:08 2015 +0000 @@ -489,6 +489,57 @@ self.assertRaises(TypeError, hash, C2()) + def testPredefinedAttrs(self): + o = object() + class Custom: + pass + c = Custom() + + methods = ( + "__new__", "__init__", + "__repr__", "__str__", "__format__", + "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", + "__hash__", + "__getattribute__", "__setattr__", "__delattr__", "__dir__", + ) + for name in methods: + with self.subTest(name): + self.assertTrue(callable(getattr(object, name))) + self.assertTrue(callable(getattr(o, name))) + self.assertTrue(callable(getattr(Custom, name))) + self.assertTrue(callable(getattr(c, name))) + + not_defined = [ + "__bool__", "__bytes__", "__del__", "__getattr__", "__len__", + "__get__", "__set__", "__delete__", "__objclass__", + "__len__", "__length_hint__", "__iter__", "__reversed__", + "__getitem__", "__setitem__", "__delitem__", + "__contains__", "__missing__", + "__divmod__", "__rdivmod__", + "__neg__", "__pos__", "__abs__", "__invert__", + "__complex__", "__int__", "__float__", "__round__", "__index__", + "__enter__", "__exit__", + "__await__", "__aiter__", "__anext__", "__aenter__", "__aexit__", + ] + augment = ( + "add", "sub", + "mul", "matmul", "truediv", "floordiv", "mod", "pow", + "lshift", "rshift", "and", "xor", "or", + ) + not_defined.extend(map("__{}__".format, augment)) + not_defined.extend(map("__r{}__".format, augment)) + not_defined.extend(map("__i{}__".format, augment)) + for name in not_defined: + with self.subTest(name): + self.assertFalse(hasattr(object, name)) + self.assertFalse(hasattr(o, name)) + self.assertFalse(hasattr(Custom, name)) + self.assertFalse(hasattr(c, name)) + + # __call__() is defined on the metaclass but not the class + self.assertFalse(hasattr(o, "__call__")) + self.assertFalse(hasattr(c, "__call__")) + def testSFBug532646(self): # Test for SF bug 532646