Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-60712: Include the "object" type in the lists of documented types#103036

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
willingc merged 30 commits intopython:mainfromfurkanonder:issue-60712
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from12 commits
Commits
Show all changes
30 commits
Select commitHold shift + click to select a range
2c09057
add test for the predefined object's attributes
furkanonderMar 25, 2023
9a71e36
Include the "object" type in the lists of documented types
furkanonderMar 25, 2023
d327409
remove 'or' from augment tuple
furkanonderMar 28, 2023
73698a5
📜🤖 Added by blurb_it.
blurb-it[bot]Mar 28, 2023
1064065
Add cross-reference to news
furkanonderMar 30, 2023
ce4d192
Fix format for the function parameter
furkanonderMar 30, 2023
aca2c04
Add space
furkanonderMar 30, 2023
f6c12d8
add reference for the 'object'
furkanonderMar 30, 2023
b1ab4a2
add reference for NotImplemented
furkanonderMar 30, 2023
d709946
Change ref:`string <textseq>` as class:`str`
furkanonderMar 31, 2023
105f331
remove hyphen from `newly-created`
furkanonderMar 31, 2023
119e29b
Update Doc/reference/datamodel.rst
terryjreedyJun 18, 2023
d8c1995
Merge branch 'main' into issue-60712
furkanonderJun 7, 2024
7762a08
Update predefined attribute types in testPredefinedAttrs
furkanonderJul 17, 2024
7ffed7c
Change `universal type` as `top type`
furkanonderJul 17, 2024
5ad51b9
Merge branch 'main' into issue-60712
furkanonderJul 20, 2024
71a2d43
Don't mention about the top type
furkanonderAug 11, 2024
2d9f0a0
Update the description of richcmpfuncs
furkanonderAug 11, 2024
10adcee
Update Doc/library/stdtypes.rst
furkanonderAug 12, 2024
f9961eb
Merge branch 'main' into issue-60712
furkanonderAug 12, 2024
ab5ef40
Revert: Hierarchy Section in Data Model Documentation
furkanonderOct 17, 2024
6681f67
Revert to original explanations of __new__ and __init__ methods in da…
furkanonderOct 20, 2024
7d68154
Merge branch 'main' into issue-60712
furkanonderOct 20, 2024
3f41130
Update Doc/reference/datamodel.rst
furkanonderOct 21, 2024
026e514
Remove blank line
furkanonderOct 21, 2024
7181046
Use ref:`str <textseq>` instead of :class:`str
furkanonderOct 21, 2024
69b710a
Merge branch 'main' into issue-60712
furkanonderOct 21, 2024
55f8c6a
Revert changes the description of Other Built-in Types in stdtypes.rst
furkanonderOct 21, 2024
b199746
Update Doc/reference/datamodel.rst
furkanonderOct 22, 2024
cf6efa1
Merge branch 'main' into issue-60712
willingcOct 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletionsDoc/library/functions.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1117,9 +1117,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::

Expand Down
3 changes: 2 additions & 1 deletionDoc/library/stdtypes.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -5207,7 +5207,8 @@ instantiated from the type::
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.


Expand Down
88 changes: 60 additions & 28 deletionsDoc/reference/datamodel.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -126,11 +126,13 @@ The standard type hierarchy
pair: extension; module
pair: C; language

Below is a list of the types that are built into Python. 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.),
although such additions will often be provided via the standard library instead.
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.), although such additions will
often be provided via the standard library instead.

.. index::
single: attribute
Expand DownExpand Up@@ -1269,10 +1271,11 @@ Basic customization
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
Typicalcustomimplementations create a new instance of the class by invoking the
superclass's :meth:`__new__` method using ``super().__new__(cls[, ...])``
with appropriate arguments and then modifying the newly created instance
as necessary before returning it.
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__` is invoked during object construction and it returns an
instance of *cls*, then the new instance’s :meth:`__init__` method
Expand All@@ -1294,9 +1297,14 @@ Basic customization
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: ``super().__init__([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 customize it),
Expand All@@ -1315,7 +1323,8 @@ Basic customization
finalizer or (improperly) 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.
class part of the instance. The :class:`object` class itself does not have a
:meth:`__del__` method.

It is possible (though not recommended!) for the :meth:`__del__` method
to postpone destruction of the instance by creating a new reference to
Expand DownExpand Up@@ -1383,7 +1392,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)
Expand All@@ -1393,10 +1403,10 @@ Basic customization

.. method:: object.__str__(self)
Copy link
Member

@merwokmerwokOct 19, 2024
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I thought we had a doc bug years ago where we came up with a convention to differentiateobject.__str__ (actual method that exists in theobject class),anyclass.__bases__ (method that exists on all class; explaining the data model) andsomeclass.__str__ (method you can define in your class to implement a protocol)

I guess we didn’t…


Called by :func:`str(object) <str>` andthebuilt-in functions
:func:`format`and :func:`print` to compute the "informal" or nicely
Called by :func:`str(object) <str>`,thedefault :meth:`__format__` implementation,
andthe 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.
:class:`str` object.

This method differs from :meth:`object.__repr__` in that there is no
expectation that :meth:`__str__` return a valid Python expression: a more
Expand All@@ -1413,7 +1423,8 @@ Basic customization
.. index:: builtin: 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)
Expand All@@ -1437,6 +1448,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.
Expand DownExpand Up@@ -1479,6 +1493,11 @@ 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:`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.
Expand DownExpand Up@@ -1530,10 +1549,10 @@ Basic customization
immutable (if the object's hash value changes, it will be in the wrong hash
bucket).

User-defined classeshave :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)``.
User-defined classes(and the :class:`object` class itself) have:meth:`__eq__`
and :meth:`__hash__` methodsby 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)``.

A class that overrides :meth:`__eq__` and does not define :meth:`__hash__`
will have its :meth:`__hash__` implicitly set to ``None``. When the
Expand DownExpand Up@@ -1583,8 +1602,8 @@ Basic customization
``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 consideredtrue.


.. _attribute-access:
Expand All@@ -1606,6 +1625,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
Expand DownExpand Up@@ -1674,7 +1694,10 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
.. 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.


Customizing module attribute access
Expand DownExpand Up@@ -1743,8 +1766,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:`__dict__`. The :class:`object` class itself does not
implement any of these protocols.

.. method:: object.__get__(self, instance, owner=None)

Expand DownExpand Up@@ -2419,17 +2442,18 @@ 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:

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>`),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

🤔 Hm… on the line before, we see a general term used (with a link to glossary) and a concrete example in parens (list and tuple links), then we have the general/glossary term mappings and should keep the specific type dict in parens to keep the intent of the text. On the other hand, if the glossary term for dictionaries is a better explanation than the dict type/function doc, and more specific than the term for mappings, the changed link could be an improvement.

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 <
Expand DownExpand Up@@ -2789,6 +2813,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)
Expand DownExpand Up@@ -2952,6 +2977,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::

Expand DownExpand Up@@ -3037,6 +3064,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.
Expand DownExpand Up@@ -3083,6 +3113,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:`__enter__`, the only
Expand Down
52 changes: 52 additions & 0 deletionsLib/test/test_class.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -503,6 +503,58 @@ def __eq__(self, other): return 1

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",
)
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
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
Include the :class:`object` type in the lists of documented types.
Change by Furkan Onder and Martin Panter.

[8]ページ先頭

©2009-2025 Movatter.jp