special recursion handling. In addition to protecting the stack,
:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
following two functions facilitate this functionality. Effectively,
-these are the C equivalent to :func:`reprlib.recursive_repr`.
+these are the C equivalent to :deco:`reprlib.recursive_repr`.
.. c:function:: int Py_ReprEnter(PyObject *object)
The method will be passed the type object as the first parameter rather
than an instance of the type. This is used to create *class methods*,
- similar to what is created when using the :func:`classmethod` built-in
- function.
+ similar to what is created when using the :deco:`classmethod` built-in
+ decorator.
.. c:macro:: METH_STATIC
The method will be passed ``NULL`` as the first parameter rather than an
instance of the type. This is used to create *static methods*, similar to
- what is created when using the :func:`staticmethod` built-in function.
+ what is created when using the :deco:`staticmethod` built-in decorator.
One other constant controls whether a method is loaded in place of another
definition with the same method name.
Use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``
to create a TypedDict with zero field.
- * The :func:`!typing.no_type_check_decorator` decorator function
+ * The :deco:`!typing.no_type_check_decorator` decorator function
has been deprecated since Python 3.13.
After eight years in the :mod:`typing` module,
it has yet to be supported by any major type checker.
----------------------------
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.
decorator
A function returning another function, usually applied as a function
transformation using the ``@wrapper`` syntax. Common examples for
- decorators are :func:`classmethod` and :func:`staticmethod`.
+ decorators are :deco:`classmethod` and :deco:`staticmethod`.
The decorator syntax is merely syntactic sugar, the following two
function definitions are semantically equivalent::
determined by the dispatch algorithm.
See also the :term:`single dispatch` glossary entry, the
- :func:`functools.singledispatch` decorator, and :pep:`443`.
+ :deco:`functools.singledispatch` decorator, and :pep:`443`.
generic type
A :term:`type` that can be parameterized; typically a
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
4) The last section has pure Python equivalents for built-in descriptors that
are written in C. Read this if you're curious about how functions turn
into bound methods or about the implementation of common tools like
- :func:`classmethod`, :func:`staticmethod`, :func:`property`, and
+ :deco:`classmethod`, :deco:`staticmethod`, :deco:`property`, and
:term:`__slots__`.
have a say in the matter.
Descriptors are used throughout the language. It is how functions turn into
-bound methods. Common tools like :func:`classmethod`, :func:`staticmethod`,
-:func:`property`, and :func:`functools.cached_property` are all implemented as
+bound methods. Common tools like :deco:`classmethod`, :deco:`staticmethod`,
+:deco:`property`, and :deco:`functools.cached_property` are all implemented as
descriptors.
30
Using the non-data descriptor protocol, a pure Python version of
-:func:`staticmethod` would look like this:
+:deco:`staticmethod` would look like this:
.. testcode::
{'a': None, 'b': None, 'r': None, 'c': None, 'd': None}
Using the non-data descriptor protocol, a pure Python version of
-:func:`classmethod` would look like this:
+:deco:`classmethod` would look like this:
.. testcode::
4. Improves speed. Reading instance variables is 35% faster with
``__slots__`` (as measured with Python 3.10 on an Apple M1 processor).
-5. Blocks tools like :func:`functools.cached_property` which require an
+5. Blocks tools like :deco:`functools.cached_property` which require an
instance dictionary to function correctly:
.. testcode::
----------------------------------
By default, enumerations allow multiple names as aliases for the same value.
-When this behavior isn't desired, you can use the :func:`unique` decorator::
+When this behavior isn't desired, you can use the :deco:`unique` decorator::
>>> from enum import Enum, unique
>>> @unique
.. 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::
:meth:`~object.__lt__` is not implemented (see :func:`object.__lt__`
for details on the mechanics). To avoid surprises, :pep:`8`
recommends that all six comparison methods be implemented.
- The :func:`~functools.total_ordering` decorator is provided to make that
+ The :deco:`~functools.total_ordering` decorator is provided to make that
task easier.
* Key functions need not depend directly on the objects being sorted. A key
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::
the descriptor must identify itself as abstract using
:attr:`!__isabstractmethod__`. In general, this attribute should be ``True``
if any of the methods used to compose the descriptor are abstract. For
- example, Python's built-in :class:`property` does the equivalent of::
+ example, Python's built-in :deco:`property` does the equivalent of::
class Descriptor:
...
.. versionadded:: 3.2
.. deprecated-removed:: 3.3 3.21
- 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 :class:`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::
.. versionadded:: 3.2
.. deprecated-removed:: 3.3 3.21
- 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 :class:`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::
.. decorator:: abstractproperty
.. deprecated-removed:: 3.3 3.21
- 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 :class:`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::
they are used. Consequently, if the search functions are used in a loop,
the key function may be called again and again on the same array elements.
If the key function isn't fast, consider wrapping it with
- :py:func:`functools.cache` to avoid duplicate computations. Alternatively,
+ :py:deco:`functools.cache` to avoid duplicate computations. Alternatively,
consider searching an array of precomputed keys to locate the insertion
point (as shown in the examples section below).
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::
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
.. decorator:: asynccontextmanager
- Similar to :func:`~contextlib.contextmanager`, but creates an
+ Similar to :deco:`~contextlib.contextmanager`, but creates an
:ref:`asynchronous context manager <async-context-managers>`.
This function is a :term:`decorator` that can be used to define a factory
.. 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
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.
``__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``::
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())
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::
>>>
If you don't want to store the instance's data in the :attr:`!_as_parameter_`
-instance variable, you could define a :class:`property` which makes the
+instance variable, you could define a :deco:`property` which makes the
attribute available on request.
: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() <str>` and :func:`repr` of an enum
to show its members as belonging to the module instead of its class,
.. 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.
functions documented below do not allow to mix a :class:`!bytes` pattern with
a :class:`!str` filename, and vice-versa.
-Finally, note that :func:`functools.lru_cache` with a *maxsize* of 32768
+Finally, note that :deco:`functools.lru_cache` with a *maxsize* of 32768
is used to cache the (typed) compiled regex patterns in the following
functions: :func:`fnmatch`, :func:`fnmatchcase`, :func:`.filter`, :func:`.filterfalse`.
If given, *doc* will be the docstring of the property attribute. Otherwise, the
property will copy *fget*'s docstring (if it exists). This makes it possible to
- create read-only properties easily using :func:`property` as a :term:`decorator`::
+ create read-only properties easily using :deco:`property` as a :term:`decorator`::
class Parrot:
def __init__(self):
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
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::
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::
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
(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
function's :attr:`~function.__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.
it is best practice to only do so in top-level applications or
:mod:`site configuration <site>`.
To set a global default this way, a filter function needs to be wrapped in
- :func:`staticmethod` to prevent injection of a ``self`` argument.
+ :deco:`staticmethod` to prevent injection of a ``self`` argument.
.. versionchanged:: 3.14
.. decorator:: anticipate_failure(condition)
A decorator to conditionally mark tests with
- :func:`unittest.expectedFailure`. Any use of this decorator should
+ :deco:`unittest.expectedFailure`. Any use of this decorator should
have an associated comment identifying the relevant tracker issue.
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. Protocol classes without this decorator cannot be used
as the second argument to :func:`isinstance` or :func:`issubclass`.
.. 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`
Decorator to mark an object as providing
:func:`dataclass <dataclasses.dataclass>`-like behavior.
- ``dataclass_transform`` may be used to
+ ``@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
decorated object performs runtime "magic" that
``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 ``@dataclass_transform`` decorator can be used to
customize the default behaviors of the decorated class, metaclass, or
function:
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.
+ ``@dataclass_transform`` will be used, or if that is unspecified, the
+ value of ``kw_only_default`` on ``@dataclass_transform`` will be used.
* - ``alias``
- Provides an alternative name for the field. This alternative
name is used in the synthesized ``__init__`` method.
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.
: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
A class method called before tests in an individual class are run.
``setUpClass`` is called with the class as the only argument
- and must be decorated as a :func:`classmethod`::
+ and must be decorated as a :deco:`classmethod`::
@classmethod
def setUpClass(cls):
A class method called after tests in an individual class have run.
``tearDownClass`` is called with the class as the only argument
- and must be decorated as a :meth:`classmethod`::
+ and must be decorated as a :deco:`classmethod`::
@classmethod
def tearDownClass(cls):
.. 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()
.. 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*
.. 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.
is not enforced by the language, and in general annotations may contain arbitrary
expressions. The presence of annotations does not change the runtime semantics of
the code, except if some mechanism is used that introspects and uses the annotations
-(such as :mod:`dataclasses` or :func:`functools.singledispatch`).
+(such as :mod:`dataclasses` or :deco:`functools.singledispatch`).
By default, annotations are lazily evaluated in an :ref:`annotation scope <annotation-scopes>`.
This means that they are not evaluated when the code containing the annotation is evaluated.
:data:`!NotImplemented`. There are no other implied relationships among the
comparison operators or default implementations; for example, the truth of
``(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`.
+ operations from a single root operation, see :deco:`functools.total_ordering`.
By default, the :class:`object` class provides implementations consistent
with :ref:`expressions-value-comparisons`: equality compares according to
override methods. This allows individual instances to acquire behaviors that
differ from other instances of the same class.
-The :func:`property` function is implemented as a data descriptor. Accordingly,
+The :deco:`property` decorator is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.
The last two expressions apply to totally ordered collections (e.g. to
sequences, but not to sets or mappings). See also the
- :func:`~functools.total_ordering` decorator.
+ :deco:`~functools.total_ordering` decorator.
* The :func:`hash` result should be consistent with equality.
Objects that are equal should either have the same hash value,
inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
This description does not necessarily apply to descriptor attributes, such as
- properties created with :func:`property`.
+ properties created with :deco:`property`.
.. index::
pair: subscription; assignment
The new :mod:`contextlib` module provides some functions and a decorator that
are useful for writing objects for use with the ':keyword:`with`' statement.
-The decorator is called :func:`contextmanager`, and lets you write a single
+The decorator is called :deco:`~contextlib.contextmanager`, and lets you write a single
generator function instead of defining a new class. The generator should yield
exactly one value. The code up to the :keyword:`yield` will be executed as the
:meth:`~object.__enter__` method, and the value yielded will be the method's return
The :mod:`contextlib` module provides some functions and a decorator that
are useful when writing objects for use with the ':keyword:`with`' statement.
-The decorator is called :func:`~contextlib.contextmanager`, and lets you write
+The decorator is called :deco:`~contextlib.contextmanager`, and lets you write
a single generator function instead of defining a new class. The generator
should yield exactly one value. The code up to the :keyword:`yield` will be
executed as the :meth:`~object.__enter__` method, and the value yielded will
.. Revision 57619
-* Properties now have three attributes, :attr:`getter`, :attr:`setter`
- and :attr:`deleter`, that are decorators providing useful shortcuts
+* Properties now have three decorators, :deco:`~property.getter`,
+ :deco:`~property.setter` and :deco:`~property.deleter`, that are
+ decorators providing useful shortcuts
for adding a getter, setter or deleter function to an existing
property. You would use them like this::
uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
:issue:`6845`.)
-* New class decorator: :func:`~functools.total_ordering` in the :mod:`functools`
+* New class decorator: :deco:`~functools.total_ordering` in the :mod:`functools`
module takes a class that defines an :meth:`~object.__eq__` method and one of
:meth:`~object.__lt__`, :meth:`~object.__le__`, :meth:`~object.__gt__`, or :meth:`~object.__ge__`,
and generates the missing comparison methods. Since the
__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
Subclasses of ``typing.Protocol`` which only have data variables declared
will now raise a ``TypeError`` when checked with ``isinstance`` unless they
-are decorated with :func:`~typing.runtime_checkable`. Previously, these checks
+are decorated with :deco:`~typing.runtime_checkable`. Previously, these checks
passed silently. Users should decorate their
-subclasses with the :func:`!runtime_checkable` decorator
+subclasses with the :deco:`!runtime_checkable` decorator
if they want runtime protocols.
(Contributed by Yurii Karabas in :issue:`38908`.)
PEP 681: Data class transforms
------------------------------
-:data:`~typing.dataclass_transform` may be used to
+:deco:`~typing.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
decorated object performs runtime "magic" that transforms a class,
* Added the :func:`~enum.member` and :func:`~enum.nonmember` decorators,
to ensure the decorated object is/is not converted to an enum member.
-* Added the :func:`~enum.property` decorator,
- which works like :func:`property` except for enums.
+* Added the :deco:`~enum.property` decorator,
+ which works like :deco:`property` except for enums.
Use this instead of :func:`types.DynamicClassAttribute`.
* Added the :func:`~enum.global_enum` enum decorator,
functools
---------
-* :func:`functools.singledispatch` now supports :class:`types.UnionType`
+* :deco:`functools.singledispatch` now supports :class:`types.UnionType`
and :class:`typing.Union` as annotations to the dispatch argument.::
>>> from functools import singledispatch
type checker errors related to highly dynamic class, such as mocks.
(Contributed by Shantanu Jain in :gh:`91154`.)
-* The :func:`typing.final` decorator now sets the ``__final__`` attributed on
+* The :deco:`typing.final` decorator now sets the ``__final__`` attributed on
the decorated object.
(Contributed by Jelle Zijlstra in :gh:`90500`.)
:data:`~typing.ClassVar` annotations. (Contributed by Gregory Beauregard
in :gh:`90711`.)
-* :func:`typing.no_type_check` no longer modifies external classes and functions.
+* :deco:`typing.no_type_check` no longer modifies external classes and functions.
It also now correctly marks classmethods as not to be type checked. (Contributed
by Nikita Sobolev in :gh:`90729`.)
* :ref:`PEP 692 <whatsnew312-pep692>`, using :class:`~typing.TypedDict` to
annotate :term:`**kwargs <argument>`
-* :ref:`PEP 698 <whatsnew312-pep698>`, :func:`typing.override` decorator
+* :ref:`PEP 698 <whatsnew312-pep698>`, :deco:`typing.override` decorator
Important deprecations, removals or restrictions:
PEP 698: Override Decorator for Static Typing
---------------------------------------------
-A new decorator :func:`typing.override` has been added to the :mod:`typing`
+A new decorator :deco:`typing.override` has been added to the :mod:`typing`
module. It indicates to type checkers that the method is intended to override
a method in a superclass. This allows type checkers to catch mistakes where
a method that is intended to override something in a base class
``__orig_bases__`` attribute. (Contributed by Adrian Garcia Badaracco in
:gh:`103699`.)
-* Add ``frozen_default`` parameter to :func:`typing.dataclass_transform`.
+* Add ``frozen_default`` parameter to :deco:`typing.dataclass_transform`.
(Contributed by Erik De Bonte in :gh:`99957`.)
unicodedata
around process-global resources, which are best managed from the main interpreter.
(Contributed by Donghee Na in :gh:`99127`.)
-* The undocumented locking behavior of :func:`~functools.cached_property`
+* The undocumented locking behavior of :deco:`~functools.cached_property`
is removed, because it locked across all instances of the class, leading to high
lock contention. This means that a cached property getter function could now run
more than once for a single instance, if two threads race. For most simple
use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``.
(Contributed by Alex Waygood in :gh:`105566` and :gh:`105570`.)
- * Deprecate the :func:`!typing.no_type_check_decorator` decorator function,
+ * Deprecate the :deco:`!typing.no_type_check_decorator` decorator function,
to be removed in Python 3.15.
After eight years in the :mod:`typing` module,
it has yet to be supported by any major type checker.
or ``TD = TypedDict("TD", {})`` instead.
(Contributed by Bénédikt Tran in :gh:`133823`.)
-* Deprecated :func:`!typing.no_type_check_decorator` has been removed.
+* Deprecated :deco:`!typing.no_type_check_decorator` has been removed.
(Contributed by Nikita Sobolev in :gh:`133601`.)
---------
* The :mod:`functools` module includes a new decorator for caching function
- calls. :func:`functools.lru_cache` can save repeated queries to an external
+ calls. :deco:`functools.lru_cache` can save repeated queries to an external
resource whenever the results are expected to be the same.
For example, adding a caching decorator to a database query function can save
<https://code.activestate.com/recipes/577479-simple-caching-decorator/>`_\, :issue:`10586`, and
:issue:`10593`.)
-* The :func:`functools.wraps` decorator now adds a :attr:`__wrapped__` attribute
+* The :deco:`functools.wraps` decorator now adds a :attr:`__wrapped__` attribute
pointing to the original callable function. This allows wrapped functions to
be introspected. It also copies :attr:`~function.__annotations__` if
defined. And now it also gracefully skips over missing attributes such as
:issue:`8814`.)
* To help write classes with rich comparison methods, a new decorator
- :func:`functools.total_ordering` will use existing equality and inequality
+ :deco:`functools.total_ordering` will use existing equality and inequality
methods to fill in the remaining methods.
For example, supplying *__eq__* and *__lt__* will enable
- :func:`~functools.total_ordering` to fill-in *__le__*, *__gt__* and *__ge__*::
+ :deco:`~functools.total_ordering` to fill-in *__le__*, *__gt__* and *__ge__*::
@total_ordering
class Student:
abc
---
-The :mod:`abc` module now supports :func:`~abc.abstractclassmethod` and
-:func:`~abc.abstractstaticmethod`.
+The :mod:`abc` module now supports :deco:`~abc.abstractclassmethod` and
+:deco:`~abc.abstractstaticmethod`.
These tools make it possible to define an :term:`abstract base class` that
-requires a particular :func:`classmethod` or :func:`staticmethod` to be
+requires a particular :deco:`classmethod` or :deco:`staticmethod` to be
implemented::
class Temperature(metaclass=abc.ABCMeta):
string.
To help write such :meth:`~object.__repr__` methods, the :mod:`reprlib` module has a new
-decorator, :func:`~reprlib.recursive_repr`, for detecting recursive calls to
+decorator, :deco:`~reprlib.recursive_repr`, for detecting recursive calls to
:meth:`!__repr__` and substituting a placeholder string instead::
>>> class MyList(list):
:term:`context manager` that does double duty as a function decorator.
As a convenience, this new functionality is used by
-:func:`~contextlib.contextmanager` so that no extra effort is needed to support
+:deco:`~contextlib.contextmanager` so that no extra effort is needed to support
both roles.
The basic idea is that both context managers and function decorators can be used
For example, it is sometimes useful to wrap functions or groups of statements
with a logger that can track the time of entry and time of exit. Rather than
writing both a function decorator and a context manager for the task, the
-:func:`~contextlib.contextmanager` provides both capabilities in a single
+:deco:`~contextlib.contextmanager` provides both capabilities in a single
definition::
from contextlib import contextmanager
now to provide :attr:`!__isabstractmethod__` as a dynamically updated
property. The built-in descriptors have been updated accordingly.
-* :class:`abc.abstractproperty` has been deprecated, use :class:`property`
- with :func:`abc.abstractmethod` instead.
-* :class:`abc.abstractclassmethod` has been deprecated, use
- :class:`classmethod` with :func:`abc.abstractmethod` instead.
-* :class:`abc.abstractstaticmethod` has been deprecated, use
- :class:`staticmethod` with :func:`abc.abstractmethod` instead.
+* :deco:`abc.abstractproperty` has been deprecated, use :deco:`property`
+ with :deco:`abc.abstractmethod` instead.
+* :deco:`abc.abstractclassmethod` has been deprecated, use
+ :deco:`classmethod` with :deco:`abc.abstractmethod` instead.
+* :deco:`abc.abstractstaticmethod` has been deprecated, use
+ :deco:`staticmethod` with :deco:`abc.abstractmethod` instead.
(Contributed by Darren Dale in :issue:`11610`.)
functools
---------
-The :func:`functools.lru_cache` decorator now accepts a ``typed`` keyword
+The :deco:`functools.lru_cache` decorator now accepts a ``typed`` keyword
argument (that defaults to ``False`` to ensure that it caches values of
different types that compare equal in separate cache slots. (Contributed
by Raymond Hettinger in :issue:`13227`.)
* The :func:`!os.stat_float_times` function is deprecated.
* :mod:`abc` module:
- * :class:`abc.abstractproperty` has been deprecated, use :class:`property`
- with :func:`abc.abstractmethod` instead.
- * :class:`abc.abstractclassmethod` has been deprecated, use
- :class:`classmethod` with :func:`abc.abstractmethod` instead.
- * :class:`abc.abstractstaticmethod` has been deprecated, use
- :class:`staticmethod` with :func:`abc.abstractmethod` instead.
+ * :deco:`abc.abstractproperty` has been deprecated, use :deco:`property`
+ with :deco:`abc.abstractmethod` instead.
+ * :deco:`abc.abstractclassmethod` has been deprecated, use
+ :deco:`classmethod` with :deco:`abc.abstractmethod` instead.
+ * :deco:`abc.abstractstaticmethod` has been deprecated, use
+ :deco:`staticmethod` with :deco:`abc.abstractmethod` instead.
* :mod:`importlib` package:
.. _whatsnew-singledispatch:
-The new :func:`~functools.singledispatch` decorator brings support for
+The new :deco:`~functools.singledispatch` decorator brings support for
single-dispatch generic functions to the Python standard library. Where
object oriented programming focuses on grouping multiple operations on a
common set of data into a class, a generic function focuses on grouping
:pep:`443` -- Single-dispatch generic functions
PEP written and implemented by Łukasz Langa.
-:func:`~functools.total_ordering` now supports a return value of
+:deco:`~functools.total_ordering` now supports a return value of
:data:`NotImplemented` from the underlying comparison function. (Contributed
by Katie Miller in :issue:`10042`.)
and Nick Coghlan in :issue:`18626`.)
:func:`~inspect.unwrap` makes it easy to unravel wrapper function chains
-created by :func:`functools.wraps` (and any other API that sets the
+created by :deco:`functools.wraps` (and any other API that sets the
``__wrapped__`` attribute on a wrapper function). (Contributed by
Daniel Urban, Aaron Iles and Nick Coghlan in :issue:`13266`.)
wish to continue to ignore syntax or decoding issues, catch all three
exceptions now.
-* :func:`functools.update_wrapper` and :func:`functools.wraps` now correctly
+* :func:`functools.update_wrapper` and :deco:`functools.wraps` now correctly
set the ``__wrapped__`` attribute to the function being wrapped, even if
that function also had its ``__wrapped__`` attribute set. This means
``__wrapped__`` attributes now correctly link a stack of decorated
:ref:`better and significantly faster way <whatsnew-pep-471>`
of directory traversal.
-* :func:`functools.lru_cache` has been mostly
+* :deco:`functools.lru_cache` has been mostly
:ref:`reimplemented in C <whatsnew-lrucache>`, yielding much better
performance.
.. _whatsnew-lrucache:
-Most of the :func:`~functools.lru_cache` machinery is now implemented in C, making
+Most of the :deco:`~functools.lru_cache` machinery is now implemented in C, making
it significantly faster. (Contributed by Matt Joiner, Alexey Kachayev, and
Serhiy Storchaka in :issue:`14373`.)
Objects from the :mod:`random` module now use 50% less memory on 64-bit
builds. (Contributed by Serhiy Storchaka in :issue:`23488`.)
-The :func:`property` getter calls are up to 25% faster.
+The :deco:`property` getter calls are up to 25% faster.
(Contributed by Joe Jevnik in :issue:`23910`.)
Instantiation of :class:`fractions.Fraction` is now up to 30% faster.
dataclasses
-----------
-The new :func:`~dataclasses.dataclass` decorator provides a way to declare
+The new :deco:`~dataclasses.dataclass` decorator provides a way to declare
*data classes*. A data class describes its attributes using class variable
annotations. Its constructor and other magic methods, such as
:meth:`~object.__repr__`, :meth:`~object.__eq__`, and
context manager than :class:`~contextlib.ExitStack`.
(Contributed by Jesse-Bakker in :issue:`10049`.)
-The new :func:`~contextlib.asynccontextmanager`,
+The new :deco:`~contextlib.asynccontextmanager`,
:class:`~contextlib.AbstractAsyncContextManager`, and
:class:`~contextlib.AsyncExitStack` have been added to
complement their synchronous counterparts. (Contributed
functools
---------
-:func:`functools.singledispatch` now supports registering implementations
+:deco:`functools.singledispatch` now supports registering implementations
using type annotations.
(Contributed by Łukasz Langa in :issue:`32227`.)
functools
---------
-:func:`functools.lru_cache` can now be used as a straight decorator rather
+:deco:`functools.lru_cache` can now be used as a straight decorator rather
than as a function returning a decorator. So both of these are now supported::
@lru_cache
(Contributed by Raymond Hettinger in :issue:`36772`.)
-Added a new :func:`functools.cached_property` decorator, for computed properties
+Added a new :deco:`functools.cached_property` decorator, for computed properties
cached for the life of the instance. ::
import functools
The :func:`inspect.getdoc` function can now find docstrings for ``__slots__``
if that attribute is a :class:`dict` where the values are docstrings.
This provides documentation options similar to what we already have
-for :func:`property`, :func:`classmethod`, and :func:`staticmethod`::
+for :deco:`property`, :deco:`classmethod`, and :deco:`staticmethod`::
class AudioClip:
__slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
...
* "Final" variables, functions, methods and classes. See :pep:`591`,
- :class:`typing.Final` and :func:`typing.final`.
+ :class:`typing.Final` and :deco:`typing.final`.
The final qualifier instructs a static type checker to restrict
subclassing, overriding, or reassignment::
pi: Final[float] = 3.1415926536
* Protocol definitions. See :pep:`544`, :class:`typing.Protocol` and
- :func:`typing.runtime_checkable`. Simple ABCs like
+ :deco:`typing.runtime_checkable`. Simple ABCs like
:class:`typing.SupportsInt` are now ``Protocol`` subclasses.
* New protocol class :class:`typing.SupportsIndex`.