From 0d6a682334f14939068f8f247946d12a34fa4268 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Tue, 7 May 2024 23:23:24 +0200 Subject: [PATCH] gh-105812: [PoC] add :deco: role and adapt some rst files --- Doc/faq/programming.rst | 8 ++--- Doc/howto/annotations.rst | 2 +- Doc/howto/enum.rst | 2 +- Doc/library/abc.rst | 36 +++++++++---------- Doc/library/collections.rst | 2 +- Doc/library/contextlib.rst | 18 +++++----- Doc/library/dataclasses.rst | 42 +++++++++++----------- Doc/library/enum.rst | 20 +++++------ Doc/library/fnmatch.rst | 2 +- Doc/library/functions.rst | 12 +++---- Doc/library/functools.rst | 46 ++++++++++++------------ Doc/library/stdtypes.rst | 4 +-- Doc/library/test.rst | 2 +- Doc/library/typing.rst | 58 +++++++++++++++--------------- Doc/library/unittest.rst | 12 +++---- Doc/reference/datamodel.rst | 2 +- Doc/tools/extensions/pyspecific.py | 9 ++++- Doc/whatsnew/3.10.rst | 2 +- 18 files changed, 143 insertions(+), 136 deletions(-) diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index 0a88c5f6384f2b..59482adb2dc7fd 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -1966,11 +1966,11 @@ How do I cache method calls? ---------------------------- The two principal tools for caching methods are -:func:`functools.cached_property` and :func:`functools.lru_cache`. The +:deco:`functools.cached_property` and :deco:`functools.lru_cache`. The former stores results at the instance level and the latter at the class level. -The *cached_property* approach only works with methods that do not take +The :deco:`!cached_property` approach only works with methods that do not take any arguments. It does not create a reference to the instance. The cached method result will be kept only as long as the instance is alive. @@ -1979,7 +1979,7 @@ method result will be released right away. The disadvantage is that if instances accumulate, so too will the accumulated method results. They can grow without bound. -The *lru_cache* approach works with methods that have :term:`hashable` +The :deco:`!lru_cache` approach works with methods that have :term:`hashable` arguments. It creates a reference to the instance unless special efforts are made to pass in weak references. @@ -2017,7 +2017,7 @@ relevant instance attributes are mutable, the *cached_property* approach can't be made to work because it cannot detect changes to the attributes. -To make the *lru_cache* approach work when the *station_id* is mutable, +To make the :deco:`lru_cache` approach work when the *station_id* is mutable, the class needs to define the :meth:`~object.__eq__` and :meth:`~object.__hash__` methods so that the cache can detect relevant attribute updates:: diff --git a/Doc/howto/annotations.rst b/Doc/howto/annotations.rst index be8c7e6c827f57..6c4d626e894043 100644 --- a/Doc/howto/annotations.rst +++ b/Doc/howto/annotations.rst @@ -149,7 +149,7 @@ on an arbitrary object ``o``: as the ``globals``, and ``dict(vars(o))`` as the ``locals``, when calling :func:`eval`. * If ``o`` is a wrapped callable using :func:`functools.update_wrapper`, - :func:`functools.wraps`, or :func:`functools.partial`, iteratively + :deco:`functools.wraps`, or :func:`functools.partial`, iteratively unwrap it by accessing either ``o.__wrapped__`` or ``o.func`` as appropriate, until you have found the root unwrapped function. * If ``o`` is a callable (but not a class), use diff --git a/Doc/howto/enum.rst b/Doc/howto/enum.rst index 30be15230fc088..1acc923e6122a9 100644 --- a/Doc/howto/enum.rst +++ b/Doc/howto/enum.rst @@ -506,7 +506,7 @@ to use the standard :func:`repr`. .. note:: - Adding :func:`~dataclasses.dataclass` decorator to :class:`Enum` + Adding :deco:`~dataclasses.dataclass` decorator to :class:`Enum` and its subclasses is not supported. It will not raise any errors, but it will produce very strange results at runtime, such as members being equal to each other:: diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst index 10e2cba50e49b0..289fc603b668fa 100644 --- a/Doc/library/abc.rst +++ b/Doc/library/abc.rst @@ -170,17 +170,17 @@ The :mod:`!abc` module also provides the following decorator: or is derived from it. A class that has a metaclass derived from :class:`!ABCMeta` cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any - of the normal 'super' call mechanisms. :func:`!abstractmethod` may be used + of the normal 'super' call mechanisms. :deco:`!abstractmethod` may be used to declare abstract methods for properties and descriptors. Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are only supported using the :func:`update_abstractmethods` function. The - :func:`!abstractmethod` only affects subclasses derived using regular + :deco:`!abstractmethod` only affects subclasses derived using regular inheritance; "virtual subclasses" registered with the ABC's :meth:`~ABCMeta.register` method are not affected. - When :func:`!abstractmethod` is applied in combination with other method + When :deco:`!abstractmethod` is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples:: @@ -242,13 +242,13 @@ The :mod:`!abc` module also supports the following legacy decorators: .. versionadded:: 3.2 .. deprecated:: 3.3 - It is now possible to use :class:`classmethod` with - :func:`abstractmethod`, making this decorator redundant. + It is now possible to use :deco:`!classmethod` with + :deco:`!abstractmethod`, making this decorator redundant. - A subclass of the built-in :func:`classmethod`, indicating an abstract - classmethod. Otherwise it is similar to :func:`abstractmethod`. + A subclass of the built-in :deco:`classmethod`, indicating an abstract + classmethod. Otherwise it is similar to :deco:`abstractmethod`. - This special case is deprecated, as the :func:`classmethod` decorator + This special case is deprecated, as the :deco:`!classmethod` decorator is now correctly identified as abstract when applied to an abstract method:: @@ -263,13 +263,13 @@ The :mod:`!abc` module also supports the following legacy decorators: .. versionadded:: 3.2 .. deprecated:: 3.3 - It is now possible to use :class:`staticmethod` with - :func:`abstractmethod`, making this decorator redundant. + It is now possible to use :deco:`!staticmethod` with + :deco:`!abstractmethod`, making this decorator redundant. - A subclass of the built-in :func:`staticmethod`, indicating an abstract - staticmethod. Otherwise it is similar to :func:`abstractmethod`. + A subclass of the built-in :deco:`staticmethod`, indicating an abstract + staticmethod. Otherwise it is similar to :deco:`abstractmethod`. - This special case is deprecated, as the :func:`staticmethod` decorator + This special case is deprecated, as the :deco:`!staticmethod` decorator is now correctly identified as abstract when applied to an abstract method:: @@ -283,14 +283,14 @@ The :mod:`!abc` module also supports the following legacy decorators: .. decorator:: abstractproperty .. deprecated:: 3.3 - It is now possible to use :class:`property`, :meth:`property.getter`, - :meth:`property.setter` and :meth:`property.deleter` with - :func:`abstractmethod`, making this decorator redundant. + It is now possible to use :deco:`property`, :deco:`property.getter`, + :deco:`property.setter` and :deco:`property.deleter` with + :deco:`abstractmethod`, making this decorator redundant. - A subclass of the built-in :func:`property`, indicating an abstract + A subclass of the built-in :deco:`!property`, indicating an abstract property. - This special case is deprecated, as the :func:`property` decorator + This special case is deprecated, as the :deco:`!property` decorator is now correctly identified as abstract when applied to an abstract method:: diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index f868799e7f5c10..8000fbdf73552d 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -1205,7 +1205,7 @@ original insertion position is changed and moved to the end:: self.move_to_end(key) An :class:`OrderedDict` would also be useful for implementing -variants of :func:`functools.lru_cache`: +variants of :deco:`functools.lru_cache`: .. testcode:: diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst index 73e53aec9cbf1c..e90fd3ebf2016a 100644 --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -88,11 +88,11 @@ Functions and classes provided: the exception has been handled, and execution will resume with the statement immediately following the :keyword:`!with` statement. - :func:`contextmanager` uses :class:`ContextDecorator` so the context managers + :deco:`!contextmanager` uses :class:`ContextDecorator` so the context managers it creates can be used as decorators as well as in :keyword:`with` statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise "one-shot" context managers - created by :func:`contextmanager` to meet the requirement that context + created by :deco:`!contextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators). .. versionchanged:: 3.2 @@ -101,7 +101,7 @@ Functions and classes provided: .. decorator:: asynccontextmanager - Similar to :func:`~contextlib.contextmanager`, but creates an + Similar to :deco:`~contextlib.contextmanager`, but creates an :ref:`asynchronous context manager `. This function is a :term:`decorator` that can be used to define a factory @@ -128,7 +128,7 @@ Functions and classes provided: .. versionadded:: 3.7 - Context managers defined with :func:`asynccontextmanager` can be used + Context managers defined with :deco:`!asynccontextmanager` can be used either as decorators or with :keyword:`async with` statements:: import time @@ -148,11 +148,11 @@ Functions and classes provided: When used as a decorator, a new generator instance is implicitly created on each function call. This allows the otherwise "one-shot" context managers - created by :func:`asynccontextmanager` to meet the requirement that context + created by :deco:`!asynccontextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators. .. versionchanged:: 3.10 - Async context managers created with :func:`asynccontextmanager` can + Async context managers created with :deco:`!asynccontextmanager` can be used as decorators. @@ -397,7 +397,7 @@ Functions and classes provided: ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional exception handling even when used as a decorator. - ``ContextDecorator`` is used by :func:`contextmanager`, so you get this + ``ContextDecorator`` is used by :deco:`contextmanager`, so you get this functionality automatically. Example of ``ContextDecorator``:: @@ -649,7 +649,7 @@ Functions and classes provided: Similar to :meth:`ExitStack.close` but properly handles awaitables. - Continuing the example for :func:`asynccontextmanager`:: + Continuing the example for :deco:`asynccontextmanager`:: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) @@ -907,7 +907,7 @@ Files are an example of effectively single use context managers, since the first :keyword:`with` statement will close the file, preventing any further IO operations using that file object. -Context managers created using :func:`contextmanager` are also single use +Context managers created using :deco:`contextmanager` are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:: diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index 7a8b83e1384e5f..e4d2b27985ed38 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -51,24 +51,24 @@ Module contents This function is a :term:`decorator` that is used to add generated :term:`special methods ` to classes, as described below. - The ``@dataclass`` decorator examines the class to find + The :deco:`!dataclass` decorator examines the class to find ``field``\s. A ``field`` is defined as a class variable that has a :term:`type annotation `. With two - exceptions described below, nothing in ``@dataclass`` + exceptions described below, nothing in :deco:`!dataclass` examines the type specified in the variable annotation. The order of the fields in all of the generated methods is the order in which they appear in the class definition. - The ``@dataclass`` decorator will add various "dunder" methods to + The :deco:`!dataclass` decorator will add various "dunder" methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created. - If ``@dataclass`` is used just as a simple decorator with no parameters, + If :deco:`!dataclass` is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this - signature. That is, these three uses of ``@dataclass`` are + signature. That is, these three uses of :deco:`!dataclass` are equivalent:: @dataclass @@ -84,7 +84,7 @@ Module contents class C: ... - The parameters to ``@dataclass`` are: + The parameters to :deco:`!dataclass` are: - *init*: If true (the default), a :meth:`~object.__init__` method will be generated. @@ -129,17 +129,17 @@ Module contents :meth:`!__hash__` implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer's intent, the existence and behavior of :meth:`!__eq__`, and the values of - the *eq* and *frozen* flags in the ``@dataclass`` decorator. + the *eq* and *frozen* flags in the :deco:`!dataclass` decorator. - By default, ``@dataclass`` will not implicitly add a :meth:`~object.__hash__` + By default, :deco:`!dataclass` will not implicitly add a :meth:`~object.__hash__` method unless it is safe to do so. Neither will it add or change an existing explicitly defined :meth:`!__hash__` method. Setting the class attribute ``__hash__ = None`` has a specific meaning to Python, as described in the :meth:`!__hash__` documentation. If :meth:`!__hash__` is not explicitly defined, or if it is set to ``None``, - then ``@dataclass`` *may* add an implicit :meth:`!__hash__` method. - Although not recommended, you can force ``@dataclass`` to create a + then :deco:`!dataclass` *may* add an implicit :meth:`!__hash__` method. + Although not recommended, you can force :deco:`!dataclass` to create a :meth:`!__hash__` method with ``unsafe_hash=True``. This might be the case if your class is logically immutable but can still be mutated. This is a specialized use case and should be considered carefully. @@ -149,7 +149,7 @@ Module contents method in your dataclass and set ``unsafe_hash=True``; this will result in a :exc:`TypeError`. - If *eq* and *frozen* are both true, by default ``@dataclass`` will + If *eq* and *frozen* are both true, by default :deco:`!dataclass` will generate a :meth:`!__hash__` method for you. If *eq* is true and *frozen* is false, :meth:`!__hash__` will be set to ``None``, marking it unhashable (which it is, since it is mutable). If *eq* is false, @@ -296,7 +296,7 @@ Module contents :func:`!field`, then the class attribute for this field will be replaced by the specified *default* value. If *default* is not provided, then the class attribute will be deleted. The intent is - that after the :func:`@dataclass ` decorator runs, the class + that after the :deco:`dataclass` decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:: @@ -397,7 +397,7 @@ Module contents :data:`typing.Any` is used for ``type``. The values of *init*, *repr*, *eq*, *order*, *unsafe_hash*, *frozen*, *match_args*, *kw_only*, *slots*, and *weakref_slot* have - the same meaning as they do in :func:`@dataclass `. + the same meaning as they do in :deco:`dataclass`. If *module* is defined, the :attr:`!__module__` attribute of the dataclass is set to that value. @@ -405,7 +405,7 @@ Module contents This function is not strictly required, because any Python mechanism for creating a new class with :attr:`!__annotations__` can - then apply the :func:`@dataclass ` function to convert that class to + then apply the :deco:`dataclass` function to convert that class to a dataclass. This function is provided as a convenience. For example:: @@ -531,7 +531,7 @@ Post-init processing def __post_init__(self): self.c = self.a + self.b -The :meth:`~object.__init__` method generated by :func:`@dataclass ` does not call base +The :meth:`~object.__init__` method generated by :deco:`dataclass` does not call base class :meth:`!__init__` methods. If the base class has an :meth:`!__init__` method that has to be called, it is common to call this method in a :meth:`__post_init__` method:: @@ -561,7 +561,7 @@ parameters to :meth:`!__post_init__`. Also see the warning about how Class variables --------------- -One of the few places where :func:`@dataclass ` actually inspects the type +One of the few places where :deco:`dataclass` actually inspects the type of a field is to determine if a field is a class variable as defined in :pep:`526`. It does this by checking if the type of the field is :data:`typing.ClassVar`. If a field is a ``ClassVar``, it is excluded @@ -574,7 +574,7 @@ module-level :func:`fields` function. Init-only variables ------------------- -Another place where :func:`@dataclass ` inspects a type annotation is to +Another place where :deco:`dataclass` inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type ``dataclasses.InitVar``. If a field is an ``InitVar``, it is considered a pseudo-field called an init-only @@ -608,7 +608,7 @@ Frozen instances ---------------- It is not possible to create truly immutable Python objects. However, -by passing ``frozen=True`` to the :func:`@dataclass ` decorator you can +by passing ``frozen=True`` to the :deco:`dataclass` decorator you can emulate immutability. In that case, dataclasses will add :meth:`~object.__setattr__` and :meth:`~object.__delattr__` methods to the class. These methods will raise a :exc:`FrozenInstanceError` when invoked. @@ -622,7 +622,7 @@ must use :meth:`!__setattr__`. Inheritance ----------- -When the dataclass is being created by the :func:`@dataclass ` decorator, +When the dataclass is being created by the :deco:`dataclass` decorator, it looks through all of the class's base classes in reverse MRO (that is, starting at :class:`object`) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. @@ -746,7 +746,7 @@ for :attr:`!x` when creating a class instance will share the same copy of :attr:`!x`. Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the -:func:`@dataclass ` decorator will raise a :exc:`ValueError` if it +:deco:`dataclass` decorator will raise a :exc:`ValueError` if it detects an unhashable default parameter. The assumption is that if a value is unhashable, it is mutable. This is a partial solution, but it does protect against many common errors. @@ -780,7 +780,7 @@ default value have the following special behaviors: :meth:`~object.__get__` or :meth:`!__set__` method is called rather than returning or overwriting the descriptor object. -* To determine whether a field contains a default value, :func:`@dataclass ` +* To determine whether a field contains a default value, :deco:`dataclass` will call the descriptor's :meth:`!__get__` method using its class access form: ``descriptor.__get__(obj=None, type=cls)``. If the descriptor returns a value in this case, it will be used as the diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst index 21f41b73086c98..62a238acbd2a44 100644 --- a/Doc/library/enum.rst +++ b/Doc/library/enum.rst @@ -101,7 +101,7 @@ Module Contents :class:`EnumCheck` An enumeration with the values ``CONTINUOUS``, ``NAMED_FLAGS``, and - ``UNIQUE``, for use with :func:`verify` to ensure various constraints + ``UNIQUE``, for use with :deco:`verify` to ensure various constraints are met by a given enumeration. :class:`FlagBoundary` @@ -116,30 +116,30 @@ Module Contents :class:`StrEnum` defaults to the lower-cased version of the member name, while other Enums default to 1 and increase from there. - :func:`~enum.property` + :deco:`~enum.property` Allows :class:`Enum` members to have attributes without conflicting with member names. The ``value`` and ``name`` attributes are implemented this way. - :func:`unique` + :deco:`unique` Enum class decorator that ensures only one name is bound to any one value. - :func:`verify` + :deco:`verify` Enum class decorator that checks user-selectable constraints on an enumeration. - :func:`member` + :deco:`member` Make ``obj`` a member. Can be used as a decorator. - :func:`nonmember` + :deco:`nonmember` Do not make ``obj`` a member. Can be used as a decorator. - :func:`global_enum` + :deco:`global_enum` Modify the :class:`str() ` and :func:`repr` of an enum to show its members as belonging to the module instead of its class, @@ -151,7 +151,7 @@ Module Contents .. versionadded:: 3.6 ``Flag``, ``IntFlag``, ``auto`` -.. versionadded:: 3.11 ``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, ``property``, ``member``, ``nonmember``, ``global_enum``, ``show_flag_values`` +.. versionadded:: 3.11 ``StrEnum``, ``EnumCheck``, ``ReprEnum``, ``FlagBoundary``, :deco:`property`, :deco:`member`, :deco:`nonmember`, :deco:`global_enum`, ``show_flag_values`` --------------- @@ -698,7 +698,7 @@ Data Types .. class:: EnumCheck - *EnumCheck* contains the options used by the :func:`verify` decorator to ensure + *EnumCheck* contains the options used by the :deco:`verify` decorator to ensure various constraints; failed constraints result in a :exc:`ValueError`. .. attribute:: UNIQUE @@ -908,7 +908,7 @@ Utilities and Decorators .. decorator:: property - A decorator similar to the built-in *property*, but specifically for + A decorator similar to the built-in :deco:`!property`, but specifically for enumerations. It allows member attributes to have the same names as members themselves. diff --git a/Doc/library/fnmatch.rst b/Doc/library/fnmatch.rst index 7cddecd5e80887..ffe81863f389ea 100644 --- a/Doc/library/fnmatch.rst +++ b/Doc/library/fnmatch.rst @@ -46,7 +46,7 @@ module. See module :mod:`glob` for pathname expansion (:mod:`glob` uses a period are not special for this module, and are matched by the ``*`` and ``?`` patterns. -Also note that :func:`functools.lru_cache` with the *maxsize* of 32768 is used to +Also note that :deco:`functools.lru_cache` with the *maxsize* of 32768 is used to cache the compiled regex patterns in the following functions: :func:`fnmatch`, :func:`fnmatchcase`, :func:`.filter`. diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 0c7ef67774cd05..1b5f73fba5b535 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -21,14 +21,14 @@ are always available. They are listed here in alphabetical order. | | **B** | | :func:`format` | | |func-memoryview|_ | | :func:`setattr` | | | :func:`bin` | | |func-frozenset|_ | | :func:`min` | | :func:`slice` | | | :func:`bool` | | | | | | :func:`sorted` | -| | :func:`breakpoint` | | **G** | | **N** | | :func:`staticmethod` | +| | :func:`breakpoint` | | **G** | | **N** | | :deco:`staticmethod` | | | |func-bytearray|_ | | :func:`getattr` | | :func:`next` | | |func-str|_ | | | |func-bytes|_ | | :func:`globals` | | | | :func:`sum` | | | | | | | **O** | | :func:`super` | | | **C** | | **H** | | :func:`object` | | | | | :func:`callable` | | :func:`hasattr` | | :func:`oct` | | **T** | | | :func:`chr` | | :func:`hash` | | :func:`open` | | |func-tuple|_ | -| | :func:`classmethod` | | :func:`help` | | :func:`ord` | | :func:`type` | +| | :deco:`classmethod` | | :func:`help` | | :func:`ord` | | :func:`type` | | | :func:`compile` | | :func:`hex` | | | | | | | :func:`complex` | | | | **P** | | **V** | | | | | **I** | | :func:`pow` | | :func:`vars` | @@ -274,7 +274,7 @@ are always available. They are listed here in alphabetical order. implied first argument. Class methods are different than C++ or Java static methods. If you want those, - see :func:`staticmethod` in this section. + see :deco:`staticmethod` in this section. For more information on class methods, see :ref:`types`. .. versionchanged:: 3.9 @@ -1551,7 +1551,7 @@ are always available. They are listed here in alphabetical order. """Get the current voltage.""" return self._voltage - The ``@property`` decorator turns the :meth:`!voltage` method into a "getter" + The :deco:`property` decorator turns the :meth:`!voltage` method into a "getter" for a read-only attribute with the same name, and it sets the docstring for *voltage* to "Get the current voltage." @@ -1775,10 +1775,10 @@ are always available. They are listed here in alphabetical order. be used in the class definition (such as ``f()``). Static methods in Python are similar to those found in Java or C++. Also, see - :func:`classmethod` for a variant that is useful for creating alternate class + :deco:`classmethod` for a variant that is useful for creating alternate class constructors. - Like all decorators, it is also possible to call ``staticmethod`` as + Like all decorators, it is also possible to call :deco:`!staticmethod` as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst index 82c970d25a7aac..02ef10b7dab11f 100644 --- a/Doc/library/functools.rst +++ b/Doc/library/functools.rst @@ -34,7 +34,7 @@ The :mod:`functools` module defines the following functions: Returns the same as ``lru_cache(maxsize=None)``, creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this is smaller and faster than - :func:`lru_cache()` with a size limit. + :deco:`lru_cache` with a size limit. For example:: @@ -64,7 +64,7 @@ The :mod:`functools` module defines the following functions: Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for the life of the instance. Similar - to :func:`property`, with the addition of caching. Useful for expensive + to :deco:`property`, with the addition of caching. Useful for expensive computed properties of instances that are otherwise effectively immutable. Example:: @@ -78,11 +78,11 @@ The :mod:`functools` module defines the following functions: def stdev(self): return statistics.stdev(self._data) - The mechanics of :func:`cached_property` are somewhat different from - :func:`property`. A regular property blocks attribute writes unless a + The mechanics of :deco:`!cached_property` are somewhat different from + :deco:`property`. A regular property blocks attribute writes unless a setter is defined. In contrast, a *cached_property* allows writes. - The *cached_property* decorator only runs on lookups and only when an + The :deco:`!cached_property` decorator only runs on lookups and only when an attribute of the same name doesn't exist. When it does run, the *cached_property* writes to the attribute with the same name. Subsequent attribute reads and writes take precedence over the *cached_property* @@ -111,14 +111,14 @@ The :mod:`functools` module defines the following functions: (as such classes don't provide a ``__dict__`` attribute at all). If a mutable mapping is not available or if space-efficient key sharing is - desired, an effect similar to :func:`cached_property` can also be achieved by - stacking :func:`property` on top of :func:`lru_cache`. See - :ref:`faq-cache-method-calls` for more details on how this differs from :func:`cached_property`. + desired, an effect similar to :deco:`!cached_property` can also be achieved by + stacking :deco:`property` on top of :deco:`lru_cache`. See + :ref:`faq-cache-method-calls` for more details on how this differs from :deco:`!cached_property`. .. versionadded:: 3.8 .. versionchanged:: 3.12 - Prior to Python 3.12, ``cached_property`` included an undocumented lock to + Prior to Python 3.12, :deco:`!cached_property` included an undocumented lock to ensure that in multi-threaded usage the getter function was guaranteed to run only once per instance. However, the lock was per-property, not per-instance, which could result in unacceptably high lock contention. In @@ -172,7 +172,7 @@ The :mod:`functools` module defines the following functions: entries. If *user_function* is specified, it must be a callable. This allows the - *lru_cache* decorator to be applied directly to a user function, leaving + :deco:`!lru_cache` decorator to be applied directly to a user function, leaving the *maxsize* at its default value of 128:: @lru_cache @@ -319,7 +319,7 @@ The :mod:`functools` module defines the following functions: This decorator makes no attempt to override methods that have been declared in the class *or its superclasses*. Meaning that if a - superclass defines a comparison operator, *total_ordering* will not + superclass defines a comparison operator, :deco:`!total_ordering` will not implement it again, even if the original method is abstract. .. versionadded:: 3.2 @@ -369,7 +369,7 @@ The :mod:`functools` module defines the following functions: like normal functions, are handled as descriptors). When *func* is a descriptor (such as a normal Python function, - :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or + :deco:`classmethod`, :deco:`staticmethod`, :deco:`abstractmethod` or another instance of :class:`partialmethod`), calls to ``__get__`` are delegated to the underlying descriptor, and an appropriate :ref:`partial object` returned as the result. @@ -436,8 +436,8 @@ The :mod:`functools` module defines the following functions: Transform a function into a :term:`single-dispatch ` :term:`generic function`. - To define a generic function, decorate it with the ``@singledispatch`` - decorator. When defining a function using ``@singledispatch``, note that the + To define a generic function, decorate it with the :deco:`singledispatch` + decorator. When defining a function using :deco:`!singledispatch`, note that the dispatch happens on the type of the first argument:: >>> from functools import singledispatch @@ -537,7 +537,7 @@ The :mod:`functools` module defines the following functions: Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. - The original function decorated with ``@singledispatch`` is registered + The original function decorated with :deco:`singledispatch` is registered for the base :class:`object` type, which means it is used if no better implementation is found. @@ -591,8 +591,8 @@ The :mod:`functools` module defines the following functions: Transform a method into a :term:`single-dispatch ` :term:`generic function`. - To define a generic method, decorate it with the ``@singledispatchmethod`` - decorator. When defining a function using ``@singledispatchmethod``, note + To define a generic method, decorate it with the :deco:`singledispatchmethod` + decorator. When defining a function using :deco:`!singledispatchmethod`, note that the dispatch happens on the type of the first non-*self* or non-*cls* argument:: @@ -609,9 +609,9 @@ The :mod:`functools` module defines the following functions: def _(self, arg: bool): return not arg - ``@singledispatchmethod`` supports nesting with other decorators such as - :func:`@classmethod`. Note that to allow for - ``dispatcher.register``, ``singledispatchmethod`` must be the *outer most* + :deco:`!singledispatchmethod` supports nesting with other decorators such as + :deco:`classmethod`. Note that to allow for + :deco:`!dispatcher.register`, :deco:`!singledispatchmethod` must be the *outer most* decorator. Here is the ``Negator`` class with the ``neg`` methods bound to the class, rather than an instance of the class:: @@ -632,8 +632,8 @@ The :mod:`functools` module defines the following functions: return not arg The same pattern can be used for other similar decorators: - :func:`@staticmethod`, - :func:`@abstractmethod`, and others. + :deco:`staticmethod`, + :deco:`~abc.abstractmethod`, and others. .. versionadded:: 3.8 @@ -651,7 +651,7 @@ The :mod:`functools` module defines the following functions: updates the wrapper function's ``__dict__``, i.e. the instance dictionary). To allow access to the original function for introspection and other purposes - (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function + (e.g. bypassing a caching decorator such as :deco:`lru_cache`), this function automatically adds a ``__wrapped__`` attribute to the wrapper that refers to the function being wrapped. diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 6c13bd015d5691..3c37a3edae7ffd 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -4876,9 +4876,9 @@ decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the :mod:`contextlib` module for some examples. -Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator +Python's :term:`generator`\s and the :deco:`contextlib.contextmanager` decorator provide a convenient way to implement these protocols. If a generator function is -decorated with the :class:`contextlib.contextmanager` decorator, it will return a +decorated with the :deco:`!contextlib.contextmanager` decorator, it will return a context manager implementing the necessary :meth:`~contextmanager.__enter__` and :meth:`~contextmanager.__exit__` methods, rather than the iterator produced by an undecorated generator function. diff --git a/Doc/library/test.rst b/Doc/library/test.rst index 92d675b48690ff..9225e2f0f2748e 100644 --- a/Doc/library/test.rst +++ b/Doc/library/test.rst @@ -1138,7 +1138,7 @@ script execution tests. Return ``True`` if ``sys.executable interpreter`` requires environment variables in order to be able to run at all. - This is designed to be used with ``@unittest.skipIf()`` to annotate tests + This is designed to be used with :deco:`unittest.skipIf` to annotate tests that need to use an ``assert_python*()`` function to launch an isolated mode (``-I``) or no environment mode (``-E``) sub-interpreter process. diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index f53080e0610cb1..da6f499d384e39 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1260,7 +1260,7 @@ These can be used as types in annotations. They all support subscription using Using ``Annotated[T, x]`` as an annotation still allows for static typechecking of ``T``, as type checkers will simply ignore the metadata ``x``. In this way, ``Annotated`` differs from the - :func:`@no_type_check ` decorator, which can also be used for + :deco:`no_type_check` decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class. @@ -2263,7 +2263,7 @@ types. func(C()) # Passes static type check See :pep:`544` for more details. Protocol classes decorated with - :func:`runtime_checkable` (described later) act as simple-minded runtime + :deco:`runtime_checkable` (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. @@ -2308,7 +2308,7 @@ types. .. note:: - :func:`!runtime_checkable` will check only the presence of the required + :deco:`!runtime_checkable` will check only the presence of the required methods or attributes, not their type signatures or types. For example, :class:`ssl.SSLObject` is a class, therefore it passes an :func:`issubclass` @@ -2591,7 +2591,7 @@ Protocols --------- The following protocols are provided by the typing module. All are decorated -with :func:`@runtime_checkable `. +with :deco:`runtime_checkable`. .. class:: SupportsAbs @@ -2747,14 +2747,14 @@ Functions and decorators field_specifiers=(), **kwargs) Decorator to mark an object as providing - :func:`dataclass `-like behavior. + :deco:`~dataclasses.dataclass`-like behavior. - ``dataclass_transform`` may be used to + :deco:`!dataclass_transform` may be used to decorate a class, metaclass, or a function that is itself a decorator. - The presence of ``@dataclass_transform()`` tells a static type checker that the + The presence of :deco:`!dataclass_transform` tells a static type checker that the decorated object performs runtime "magic" that transforms a class in a similar way to - :func:`@dataclasses.dataclass `. + :deco:`!dataclasses.dataclass`. Example usage with a decorator function: @@ -2792,19 +2792,19 @@ Functions and decorators The ``CustomerModel`` classes defined above will be treated by type checkers similarly to classes created with - :func:`@dataclasses.dataclass `. + :deco:`dataclasses.dataclass`. For example, type checkers will assume these classes have ``__init__`` methods that accept ``id`` and ``name``. The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the - :func:`@dataclasses.dataclass` decorator: ``init``, + :deco:`!dataclasses.dataclass` decorator: ``init``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``, ``kw_only``, and ``slots``. It must be possible for the value of these arguments (``True`` or ``False``) to be statically evaluated. - The arguments to the ``dataclass_transform`` decorator can be used to + The arguments to the :deco:`!dataclass_transform` decorator can be used to customize the default behaviors of the decorated class, metaclass, or function: @@ -2868,8 +2868,8 @@ Functions and decorators keyword-only. If ``True``, the field will be keyword-only. If ``False``, it will not be keyword-only. If unspecified, the value of the ``kw_only`` parameter on the object decorated with - ``dataclass_transform`` will be used, or if that is unspecified, the - value of ``kw_only_default`` on ``dataclass_transform`` will be used. + :deco:`dataclass_transform` will be used, or if that is unspecified, the + value of ``kw_only_default`` on :deco:`!dataclass_transform` will be used. * - ``alias`` - Provides an alternative name for the field. This alternative name is used in the synthesized ``__init__`` method. @@ -2888,17 +2888,17 @@ Functions and decorators Decorator for creating overloaded functions and methods. - The ``@overload`` decorator allows describing functions and methods + The :deco:`overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series - of ``@overload``-decorated definitions must be followed by exactly one - non-``@overload``-decorated definition (for the same function/method). + of :deco:`!overload`-decorated definitions must be followed by exactly one + non-:deco:`!overload`-decorated definition (for the same function/method). - ``@overload``-decorated definitions are for the benefit of the + :deco:`!overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the - non-``@overload``-decorated definition. The non-``@overload``-decorated + non-:deco:`!overload`-decorated definition. The non-:deco:`!overload`-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling - an ``@overload``-decorated function directly will raise + an :deco:`!overload`-decorated function directly will raise :exc:`NotImplementedError`. An example of overload that gives a more @@ -2927,12 +2927,12 @@ Functions and decorators .. function:: get_overloads(func) - Return a sequence of :func:`@overload `-decorated definitions for + Return a sequence of :deco:`overload`-decorated definitions for *func*. *func* is the function object for the implementation of the overloaded function. For example, given the definition of ``process`` in - the documentation for :func:`@overload `, + the documentation for :deco:`!overload`, ``get_overloads(process)`` will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, ``get_overloads()`` returns an empty sequence. @@ -2956,8 +2956,8 @@ Functions and decorators Decorator to indicate final methods and final classes. - Decorating a method with ``@final`` indicates to a type checker that the - method cannot be overridden in a subclass. Decorating a class with ``@final`` + Decorating a method with :deco:`final` indicates to a type checker that the + method cannot be overridden in a subclass. Decorating a class with :deco:`!final` indicates that it cannot be subclassed. For example:: @@ -3000,17 +3000,17 @@ Functions and decorators checkers will ignore all annotations in a function or class with this decorator. - ``@no_type_check`` mutates the decorated object in place. + :deco:`!no_type_check` mutates the decorated object in place. .. decorator:: no_type_check_decorator - Decorator to give another decorator the :func:`no_type_check` effect. + Decorator to give another decorator the :deco:`no_type_check` effect. This wraps the decorator with something that wraps the decorated - function in :func:`no_type_check`. + function in :deco:`!no_type_check`. .. deprecated-removed:: 3.13 3.15 - No type checker ever added support for ``@no_type_check_decorator``. It + No type checker ever added support for :deco:`!no_type_check_decorator`. It is therefore deprecated, and will be removed in Python 3.15. .. decorator:: override @@ -3018,7 +3018,7 @@ Functions and decorators Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass. - Type checkers should emit an error if a method decorated with ``@override`` + Type checkers should emit an error if a method decorated with :deco:`!override` does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class. @@ -3891,7 +3891,7 @@ convenience. This is subject to change, and not all deprecations are listed. - 3.12 - Undecided - :pep:`695` - * - :func:`@typing.no_type_check_decorator ` + * - :deco:`typing.no_type_check_decorator` - 3.13 - 3.15 - :gh:`106309` diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst index 3af29f19c802c7..da846f77fb9f49 100644 --- a/Doc/library/unittest.rst +++ b/Doc/library/unittest.rst @@ -540,7 +540,7 @@ tests. In addition, it supports marking a test as an "expected failure," a test that is broken and will fail, but shouldn't be counted as a failure on a :class:`TestResult`. -Skipping a test is simply a matter of using the :func:`skip` :term:`decorator` +Skipping a test is simply a matter of using the :deco:`skip` :term:`decorator` or one of its conditional variants, calling :meth:`TestCase.skipTest` within a :meth:`~TestCase.setUp` or test method, or raising :exc:`SkipTest` directly. @@ -591,7 +591,7 @@ Classes can be skipped just like methods:: :meth:`TestCase.setUp` can also skip the test. This is useful when a resource that needs to be set up is not available. -Expected failures use the :func:`expectedFailure` decorator. :: +Expected failures use the :deco:`expectedFailure` decorator. :: class ExpectedFailureTestCase(unittest.TestCase): @unittest.expectedFailure @@ -633,7 +633,7 @@ The following decorators and exception implement test skipping and expected fail This exception is raised to skip a test. - Usually you can use :meth:`TestCase.skipTest` or one of the skipping + Usually you can use :deco:`TestCase.skipTest` or one of the skipping decorators instead of raising this directly. Skipped tests will not have :meth:`~TestCase.setUp` or :meth:`~TestCase.tearDown` run around them. @@ -2072,7 +2072,7 @@ Loading and running tests .. versionchanged:: 3.4 Returns ``False`` if there were any :attr:`unexpectedSuccesses` - from tests marked with the :func:`expectedFailure` decorator. + from tests marked with the :deco:`expectedFailure` decorator. .. method:: stop() @@ -2155,7 +2155,7 @@ Loading and running tests .. method:: addExpectedFailure(test, err) Called when the test case *test* fails or errors, but was marked with - the :func:`expectedFailure` decorator. + the :deco:`expectedFailure` decorator. The default implementation appends a tuple ``(test, formatted_err)`` to the instance's :attr:`expectedFailures` attribute, where *formatted_err* @@ -2165,7 +2165,7 @@ Loading and running tests .. method:: addUnexpectedSuccess(test) Called when the test case *test* was marked with the - :func:`expectedFailure` decorator, but succeeded. + :deco:`expectedFailure` decorator, but succeeded. The default implementation appends the test to the instance's :attr:`unexpectedSuccesses` attribute. diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index f5e87160732056..fbb8a9ed7d235c 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -2222,7 +2222,7 @@ instance dictionary. In contrast, non-data descriptors can be overridden by instances. Python methods (including those decorated with -:func:`@staticmethod ` and :func:`@classmethod `) are +:deco:`staticmethod` and :deco:`classmethod`) are implemented as non-data descriptors. Accordingly, instances can redefine and override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class. diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py index 44db77af5d24d3..9c89e0b0d824cc 100644 --- a/Doc/tools/extensions/pyspecific.py +++ b/Doc/tools/extensions/pyspecific.py @@ -21,7 +21,7 @@ from docutils.utils import new_document from sphinx import addnodes from sphinx.builders import Builder -from sphinx.domains.python import PyFunction, PyMethod +from sphinx.domains.python import PyFunction, PyMethod, PyXRefRole from sphinx.errors import NoUri from sphinx.locale import _ as sphinx_gettext from sphinx.util import logging @@ -691,9 +691,16 @@ def patch_pairindextypes(app, _env) -> None: pairindextypes.clear() +class PyDecoratorRole(PyXRefRole): + def process_link(self, *args, **kwds): + title, target = super().process_link(*args, **kwds) + return f"@{title}", target + + def setup(app): app.add_role('issue', issue_role) app.add_role('gh', gh_issue_role) + app.add_role_to_domain('py', 'deco', PyDecoratorRole()) app.add_directive('impl-detail', ImplementationDetail) app.add_directive('availability', Availability) app.add_directive('audit-event', AuditEvent) diff --git a/Doc/whatsnew/3.10.rst b/Doc/whatsnew/3.10.rst index b939ccd17903f2..f9c13ce8c35d2d 100644 --- a/Doc/whatsnew/3.10.rst +++ b/Doc/whatsnew/3.10.rst @@ -995,7 +995,7 @@ dataclasses __slots__ ~~~~~~~~~ -Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator. +Added ``slots`` parameter in :deco:`dataclasses.dataclass` decorator. (Contributed by Yurii Karabas in :issue:`42269`) Keyword-only fields