]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-60712: Include the "object" type in the lists of documented types (GH-10303...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 30 Oct 2024 20:15:24 +0000 (21:15 +0100)
committerGitHub <noreply@github.com>
Wed, 30 Oct 2024 20:15:24 +0000 (13:15 -0700)
gh-60712: Include the "object" type in the lists of documented types (GH-103036)

* add test for the predefined object's attributes

* Include the "object" type in the lists of documented types

* remove 'or' from augment tuple

* ๐Ÿ“œ๐Ÿค– Added by blurb_it.

* Add cross-reference to news

* Fix format for the function parameter

* Add space

* add reference for the 'object'

* add reference for NotImplemented

* Change ref:`string <textseq>`  as class:`str`

* remove hyphen from `newly-created`

* Update Doc/reference/datamodel.rst

'dictionaries' to 'dict'

* Update predefined attribute types in testPredefinedAttrs

* Change `universal type` as `top type`

* Don't mention about the top type

* Update the description of richcmpfuncs

* Update Doc/library/stdtypes.rst

* Revert: Hierarchy Section in Data Model Documentation

* Revert to original explanations of __new__ and __init__ methods in datamodel.rst for improved clarity.

* Update Doc/reference/datamodel.rst

* Remove blank line

* Use ref:`str <textseq>` instead of :class:`str

* Revert changes the description of Other Built-in Types in stdtypes.rst

* Update Doc/reference/datamodel.rst

---------

(cherry picked from commit 4f826214b30ad50365f45bf07e4a02f34f897ab5)

Co-authored-by: Furkan Onder <furkanonder@protonmail.com>
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Co-authored-by: C.A.M. Gerlach <CAM.Gerlach@Gerlach.CAM>
Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
Co-authored-by: ร‰ric <merwok@netwok.org>
Co-authored-by: Carol Willing <carolcode@willingconsulting.com>
Doc/library/functions.rst
Doc/reference/datamodel.rst
Lib/test/test_class.py
Misc/NEWS.d/next/Documentation/2023-03-28-22-24-45.gh-issue-60712.So5uad.rst [new file with mode: 0644]

index 3b7c9645d1496c45224dc7373fe4fc043a5fcc9a..d26e79d12fc159532208e373e31e83f255032287 100644 (file)
@@ -1223,9 +1223,10 @@ are always available.  They are listed here in alphabetical order.
 
 .. class:: object()
 
-   Return a new featureless object.  :class:`object` is a base for all classes.
-   It has 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::
 
index 7c0719bd93d5da0e793720886d78ecc1d23d4a15..bc287e1e7cdcf9409592db907d305ba8cdb60d4d 100644 (file)
@@ -1942,7 +1942,8 @@ Basic customization
    "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)
@@ -1952,10 +1953,10 @@ Basic customization
 
 .. method:: object.__str__(self)
 
-   Called by :func:`str(object) <str>` and the built-in functions
-   :func:`format` and :func:`print` to compute the "informal" or nicely
+   Called by :func:`str(object) <str>`, 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 <textseq>` object.
+   :ref:`str <textseq>` object.
 
    This method differs from :meth:`object.__repr__` in that there is no
    expectation that :meth:`__str__` return a valid Python expression: a more
@@ -1972,7 +1973,8 @@ Basic customization
    .. index:: pair: built-in function; bytes
 
    Called by :ref:`bytes <func-bytes>` to compute a byte-string representation
-   of an object. This should return a :class:`bytes` object.
+   of an object. This should return a :class:`bytes` object. The :class:`object`
+   class itself does not provide this method.
 
    .. index::
       single: string; __format__() (object method)
@@ -1996,6 +1998,9 @@ Basic customization
 
    The return value must be a string object.
 
+   The default implementation by the :class:`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.
@@ -2038,6 +2043,12 @@ Basic customization
    ``(x<y or x==y)`` does not imply ``x<=y``. 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:`expressions-value-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
+   :data:`NotImplemented`.
+
    See the paragraph on :meth:`__hash__` for
    some important notes on creating :term:`hashable` objects which support
    custom comparison operations and are usable as dictionary keys.
@@ -2093,9 +2104,9 @@ Basic customization
    bucket).
 
    User-defined classes 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)``.
+   by default (inherited from the :class:`object` class); 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)``.
 
    A class that overrides :meth:`__eq__` and does not define :meth:`__hash__`
    will have its :meth:`__hash__` implicitly set to ``None``.  When the
@@ -2145,8 +2156,8 @@ Basic customization
    ``bool()``; should return ``False`` or ``True``.  When this method is not
    defined, :meth:`~object.__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:
@@ -2168,6 +2179,7 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
    for ``self``; or :meth:`__get__` of a *name* property raises
    :exc:`AttributeError`).  This method should either 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
@@ -2306,8 +2318,8 @@ method (a so-called *descriptor* class) appears in an *owner* class (the
 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:`~object.__dict__`.
-
+class' :attr:`~object.__dict__`.  The :class:`object` class itself does not
+implement any of these protocols.
 
 .. method:: object.__get__(self, instance, owner=None)
 
@@ -2999,6 +3011,7 @@ Emulating callable objects
 
    Called when the instance is "called" as a function; if this method is defined,
    ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, arg1, ...)``.
+   The :class:`object` class itself does not provide this method.
 
 
 .. _sequence-types:
@@ -3006,10 +3019,11 @@ Emulating callable objects
 Emulating container types
 -------------------------
 
-The following methods can be defined to implement container objects.  Containers
-usually are :term:`sequences <sequence>` (such as :class:`lists <list>` or
+The following methods can be defined to implement container objects. None of them
+are provided by the :class:`object` class itself. Containers usually are
+:term:`sequences <sequence>` (such as :class:`lists <list>` or
 :class:`tuples <tuple>`) or :term:`mappings <mapping>` (like
-:class:`dictionaries <dict>`),
+:term:`dictionaries <dictionary>`),
 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
 a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
@@ -3372,6 +3386,7 @@ Typical uses of context managers include saving and restoring various kinds of
 global state, locking and unlocking resources, closing opened files, etc.
 
 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)
@@ -3576,6 +3591,8 @@ are awaitable.
    Must return an :term:`iterator`.  Should be used to implement
    :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.
 
    .. note::
 
@@ -3661,6 +3678,9 @@ its ``__anext__`` method.
 
 Asynchronous iterators can be used in an :keyword:`async for` statement.
 
+The :class:`object` class itself does not provide these methods.
+
+
 .. method:: object.__aiter__(self)
 
    Must return an *asynchronous iterator* object.
@@ -3707,6 +3727,8 @@ suspend execution in its ``__aenter__`` and ``__aexit__`` methods.
 
 Asynchronous context managers can be used in an :keyword:`async with` statement.
 
+The :class:`object` class itself does not provide these methods.
+
 .. method:: object.__aenter__(self)
 
    Semantically similar to :meth:`~object.__enter__`, the only
index 7a159760e98e25f11c8b5c2efdf8da3845cf913b..28d3c0db12c19e4bae9bc4e5192030bcaa9dfeeb 100644 (file)
@@ -503,6 +503,56 @@ class ClassTests(unittest.TestCase):
 
         self.assertRaises(TypeError, hash, C2())
 
+    def testPredefinedAttrs(self):
+        o = object()
+
+        class Custom:
+            pass
+
+        c = Custom()
+
+        methods = (
+            '__class__', '__delattr__', '__dir__', '__eq__', '__format__',
+            '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__',
+            '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__',
+            '__new__', '__reduce__', '__reduce_ex__', '__repr__',
+            '__setattr__', '__sizeof__', '__str__', '__subclasshook__'
+        )
+        for name in methods:
+            with self.subTest(name):
+                self.assertTrue(callable(getattr(object, name, None)))
+                self.assertTrue(callable(getattr(o, name, None)))
+                self.assertTrue(callable(getattr(Custom, name, None)))
+                self.assertTrue(callable(getattr(c, name, None)))
+
+        not_defined = [
+            '__abs__', '__aenter__', '__aexit__', '__aiter__', '__anext__',
+            '__await__', '__bool__', '__bytes__', '__ceil__',
+            '__complex__', '__contains__', '__del__', '__delete__',
+            '__delitem__', '__divmod__', '__enter__', '__exit__',
+            '__float__', '__floor__', '__get__', '__getattr__', '__getitem__',
+            '__index__', '__int__', '__invert__', '__iter__', '__len__',
+            '__length_hint__', '__missing__', '__neg__', '__next__',
+            '__objclass__', '__pos__', '__rdivmod__', '__reversed__',
+            '__round__', '__set__', '__setitem__', '__trunc__'
+        ]
+        augment = (
+            'add', 'and', 'floordiv', 'lshift', 'matmul', 'mod', 'mul', 'pow',
+            'rshift', 'sub', 'truediv', 'xor'
+        )
+        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
diff --git a/Misc/NEWS.d/next/Documentation/2023-03-28-22-24-45.gh-issue-60712.So5uad.rst b/Misc/NEWS.d/next/Documentation/2023-03-28-22-24-45.gh-issue-60712.So5uad.rst
new file mode 100644 (file)
index 0000000..e401cc2
--- /dev/null
@@ -0,0 +1,2 @@
+Include the :class:`object` type in the lists of documented types.
+Change by Furkan Onder and Martin Panter.