Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
gh-123523: Rework typing documentation for generators and coroutines, and link to it from collections.abc docs#123544
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AlexWaygood
merged 18 commits into
python:main
from
sterliakov:docs/gh-123523-pep585-typing-docsSep 6, 2024
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
412c358
Move typing docs for deprecated aliases to collections.abc
sterliakov 3a71312
Do the same with `contextlib` references
sterliakov c146cbd
Add a generators&coroutines section
sterliakov 8b6f65c
Replace PEP695 parameters with Generic inheritance
sterliakov 5aa430c
Remove type arguments for now
sterliakov fb13736
Revert "Do the same with `contextlib` references"
sterliakov e7bd7b7
Use double backticks
sterliakov 5c513aa
Address review comments
sterliakov c827599
s/details of/details on/g
sterliakov 8bac826
Address other review comments
sterliakov a65f256
Remove "This type may be used as follows" notes from List, Dict and M…
sterliakov dfa8564
Remove deprecated alias to `typing.Callable` from `collections.abc` r…
sterliakov 7de2e02
Add deprecation notice to `typing.Callable` and `typing.Type` recomme…
sterliakov 587d240
Use simple link
sterliakov e35d682
Reference modern `collections.abc` aliases
sterliakov fc16d76
Use fully qualified name for `collections.abc.Set` to avoid confusion…
sterliakov 24ff30e
s/Refer to/See
sterliakov e63c976
Disambiguate `typing.Set` and `collections.abc.Set`
sterliakov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -208,7 +208,7 @@ Annotating callable objects | ||
| =========================== | ||
| Functions -- or other :term:`callable` objects -- can be annotated using | ||
| :class:`collections.abc.Callable` or :data:`typing.Callable`. | ||
| :class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. | ||
| ``Callable[[int], str]`` signifies a function that takes a single parameter | ||
| of type :class:`int` and returns a :class:`str`. | ||
| @@ -401,7 +401,7 @@ The type of class objects | ||
| ========================= | ||
| A variable annotated with ``C`` may accept a value of type ``C``. In | ||
| contrast, a variable annotated with ``type[C]`` (or | ||
| contrast, a variable annotated with ``type[C]`` (or deprecated | ||
| :class:`typing.Type[C] <Type>`) may accept values that are classes | ||
| themselves -- specifically, it will accept the *class object* of ``C``. For | ||
| example:: | ||
| @@ -441,6 +441,87 @@ For example:: | ||
| ``type[Any]`` is equivalent to :class:`type`, which is the root of Python's | ||
| :ref:`metaclass hierarchy <metaclasses>`. | ||
| .. _annotating-generators-and-coroutines: | ||
| Annotating generators and coroutines | ||
| ==================================== | ||
| A generator can be annotated using the generic type | ||
| :class:`Generator[YieldType, SendType, ReturnType] <collections.abc.Generator>`. | ||
| For example:: | ||
| def echo_round() -> Generator[int, float, str]: | ||
| sent = yield 0 | ||
| while sent >= 0: | ||
| sent = yield round(sent) | ||
| return 'Done' | ||
| Note that unlike many other generic classes in the standard library, | ||
| the ``SendType`` of :class:`~collections.abc.Generator` behaves | ||
| contravariantly, not covariantly or invariantly. | ||
| The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`:: | ||
| def infinite_stream(start: int) -> Generator[int]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| It is also possible to set these types explicitly:: | ||
| def infinite_stream(start: int) -> Generator[int, None, None]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| Simple generators that only ever yield values can also be annotated | ||
| as having a return type of either | ||
| :class:`Iterable[YieldType] <collections.abc.Iterable>` | ||
| or :class:`Iterator[YieldType] <collections.abc.Iterator>`:: | ||
| def infinite_stream(start: int) -> Iterator[int]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| Async generators are handled in a similar fashion, but don't | ||
| expect a ``ReturnType`` type argument | ||
| (:class:`AsyncGenerator[YieldType, SendType] <collections.abc.AsyncGenerator>`). | ||
| The ``SendType`` argument defaults to :const:`!None`, so the following definitions | ||
| are equivalent:: | ||
| async def infinite_stream(start: int) -> AsyncGenerator[int]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| async def infinite_stream(start: int) -> AsyncGenerator[int, None]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| As in the synchronous case, | ||
| :class:`AsyncIterable[YieldType] <collections.abc.AsyncIterable>` | ||
| and :class:`AsyncIterator[YieldType] <collections.abc.AsyncIterator>` are | ||
| available as well:: | ||
| async def infinite_stream(start: int) -> AsyncIterator[int]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| Coroutines can be annotated using | ||
| :class:`Coroutine[YieldType, SendType, ReturnType] <collections.abc.Coroutine>`. | ||
| Generic arguments correspond to those of :class:`~collections.abc.Generator`, | ||
| for example:: | ||
| from collections.abc import Coroutine | ||
| c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere | ||
| x = c.send('hi') # Inferred type of 'x' is list[str] | ||
| async def bar() -> None: | ||
| y = await c # Inferred type of 'y' is int | ||
| .. _user-defined-generics: | ||
| User-defined generic types | ||
| @@ -3318,14 +3399,9 @@ Aliases to built-in types | ||
| Deprecated alias to :class:`dict`. | ||
| Note that to annotate arguments, it is preferred | ||
| to use an abstract collection type such as :class:`Mapping` | ||
| to use an abstract collection type such as :class:`~collections.abc.Mapping` | ||
| rather than to use :class:`dict` or :class:`!typing.Dict`. | ||
| This type can be used as follows:: | ||
| def count_words(text: str) -> Dict[str, int]: | ||
| ... | ||
| .. deprecated:: 3.9 | ||
| :class:`builtins.dict <dict>` now supports subscripting (``[]``). | ||
| See :pep:`585` and :ref:`types-genericalias`. | ||
| @@ -3335,16 +3411,9 @@ Aliases to built-in types | ||
| Deprecated alias to :class:`list`. | ||
| Note that to annotate arguments, it is preferred | ||
| to use an abstract collection type such as :class:`Sequence` or | ||
| :class:`Iterable` rather than to use :class:`list` or :class:`!typing.List`. | ||
| This type may be used as follows:: | ||
| def vec2[T: (int, float)](x: T, y: T) -> List[T]: | ||
| return [x, y] | ||
| def keep_positives[T: (int, float)](vector: Sequence[T]) -> List[T]: | ||
| return [item for item in vector if item > 0] | ||
| to use an abstract collection type such as | ||
| :class:`~collections.abc.Sequence` or :class:`~collections.abc.Iterable` | ||
| rather than to use :class:`list` or :class:`!typing.List`. | ||
| .. deprecated:: 3.9 | ||
| :class:`builtins.list <list>` now supports subscripting (``[]``). | ||
| @@ -3355,8 +3424,8 @@ Aliases to built-in types | ||
| Deprecated alias to :class:`builtins.set <set>`. | ||
| Note that to annotate arguments, it is preferred | ||
| to use an abstract collection type such as :class:`AbstractSet` | ||
| rather than to use :class:`set` or :class:`!typing.Set`. | ||
| to use an abstract collection type such as :class:`collections.abc.Set` | ||
| rather than to use :class:`set` or :class:`typing.Set`. | ||
| .. deprecated:: 3.9 | ||
| :class:`builtins.set <set>` now supports subscripting (``[]``). | ||
| @@ -3544,11 +3613,6 @@ Aliases to container ABCs in :mod:`collections.abc` | ||
| Deprecated alias to :class:`collections.abc.Mapping`. | ||
| This type can be used as follows:: | ||
| def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: | ||
| return word_list[word] | ||
| .. deprecated:: 3.9 | ||
| :class:`collections.abc.Mapping` now supports subscripting (``[]``). | ||
| See :pep:`585` and :ref:`types-genericalias`. | ||
| @@ -3612,14 +3676,9 @@ Aliases to asynchronous ABCs in :mod:`collections.abc` | ||
| Deprecated alias to :class:`collections.abc.Coroutine`. | ||
| The variance and order of type variables | ||
| correspond to those of :class:`Generator`, for example:: | ||
| from collections.abc import Coroutine | ||
| c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere | ||
| x = c.send('hi') # Inferred type of 'x' is list[str] | ||
| async def bar() -> None: | ||
| y = await c # Inferred type of 'y' is int | ||
| See :ref:`annotating-generators-and-coroutines` | ||
AlexWaygood marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| for details on using :class:`collections.abc.Coroutine` | ||
| and ``typing.Coroutine`` in type annotations. | ||
| .. versionadded:: 3.5.3 | ||
| @@ -3631,40 +3690,9 @@ Aliases to asynchronous ABCs in :mod:`collections.abc` | ||
| Deprecated alias to :class:`collections.abc.AsyncGenerator`. | ||
| An async generator can be annotated by the generic type | ||
| ``AsyncGenerator[YieldType, SendType]``. For example:: | ||
| async def echo_round() -> AsyncGenerator[int, float]: | ||
| sent = yield 0 | ||
| while sent >= 0.0: | ||
| rounded = await round(sent) | ||
| sent = yield rounded | ||
| Unlike normal generators, async generators cannot return a value, so there | ||
| is no ``ReturnType`` type parameter. As with :class:`Generator`, the | ||
| ``SendType`` behaves contravariantly. | ||
| The ``SendType`` defaults to :const:`!None`:: | ||
| async def infinite_stream(start: int) -> AsyncGenerator[int]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| It is also possible to set this type explicitly:: | ||
| async def infinite_stream(start: int) -> AsyncGenerator[int, None]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| Alternatively, annotate your generator as having a return type of | ||
| either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``:: | ||
| async def infinite_stream(start: int) -> AsyncIterator[int]: | ||
| while True: | ||
| yield start | ||
| start = await increment(start) | ||
| See :ref:`annotating-generators-and-coroutines` | ||
| for details on using :class:`collections.abc.AsyncGenerator` | ||
| and ``typing.AsyncGenerator`` in type annotations. | ||
| .. versionadded:: 3.6.1 | ||
| @@ -3746,40 +3774,9 @@ Aliases to other ABCs in :mod:`collections.abc` | ||
| Deprecated alias to :class:`collections.abc.Generator`. | ||
| A generator can be annotated by the generic type | ||
| ``Generator[YieldType, SendType, ReturnType]``. For example:: | ||
| def echo_round() -> Generator[int, float, str]: | ||
| sent = yield 0 | ||
| while sent >= 0: | ||
| sent = yield round(sent) | ||
| return 'Done' | ||
| Note that unlike many other generics in the typing module, the ``SendType`` | ||
| of :class:`Generator` behaves contravariantly, not covariantly or | ||
| invariantly. | ||
| The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`:: | ||
| def infinite_stream(start: int) -> Generator[int]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| It is also possible to set these types explicitly:: | ||
| def infinite_stream(start: int) -> Generator[int, None, None]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| Alternatively, annotate your generator as having a return type of | ||
| either ``Iterable[YieldType]`` or ``Iterator[YieldType]``:: | ||
| def infinite_stream(start: int) -> Iterator[int]: | ||
| while True: | ||
| yield start | ||
| start += 1 | ||
| See :ref:`annotating-generators-and-coroutines` | ||
| for details on using :class:`collections.abc.Generator` | ||
| and ``typing.Generator`` in type annotations. | ||
| .. deprecated:: 3.9 | ||
| :class:`collections.abc.Generator` now supports subscripting (``[]``). | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.