Skip to content

Commit db97dc4

Browse files
authored
Add Aliasing Decorators section to libraries.rst
I believe I'm not the only one who will struggle with behavior of `Callable` type aliases. I hope if this is added to the documentation - some people will save an hour on figuring how `TypeAlias` work. I'm not sure if it is worth introducing "decorator factory" term here, but it is used in [mypy documentation](https://mypy.readthedocs.io/en/stable/generics.html#decorator-factories). Related discussion: #1236
1 parent c7b0a54 commit db97dc4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

docs/source/libraries.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,36 @@ original signature, thus blinding type checkers and other tools that
490490
provide signature assistance. As such, library authors are discouraged
491491
from creating decorators that mutate function signatures in this manner.
492492

493+
Aliasing Decorators
494+
-------------------
495+
496+
When writing a library with a couple of decorator factories
497+
(i.e. functions returning decorators, like ``complex_decorator`` from
498+
Annotating Decorators section) it may be tempting to create a shortcut
499+
for a decorator.
500+
501+
Different type checkers handle ``TypeAlias`` involving ``Callable`` in a
502+
different manner, so the most portable and easy way to create a shortcut
503+
is to define a callable ``Protocol`` as described in `PEP
504+
544 <https://peps.python.org/pep-0544/#callback-protocols>`_:
505+
506+
.. code:: python
507+
508+
_F = TypeVar("_F", bound=Callable[..., Any])
509+
510+
class PDecorator(Protocol):
511+
def __call__(self, _: _F, /) -> _F:
512+
...
513+
514+
def decorator_factory(*, mode: str) -> PDecorator:
515+
"""
516+
Decorator factory is invoked with arguments like this:
517+
@decorator_factory(mode="easy")
518+
def my_function(): ...
519+
"""
520+
...
521+
522+
493523
Generic Classes and Functions
494524
-----------------------------
495525

0 commit comments

Comments
 (0)