8000 Improve code examples in `typing.rst` (#105346) · python/cpython@81c8132 · GitHub
[go: up one dir, main page]

Skip to content

Commit 81c8132

Browse files
authored
Improve code examples in typing.rst (#105346)
1 parent d764512 commit 81c8132

File tree

1 file changed

+75
-30
lines changed

1 file changed

+75
-30
lines changed

Doc/library/typing.rst

Lines changed: 75 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
:mod:`typing` --- Support for type hints
33
========================================
44

5+
.. testsetup:: *
6+
7+
import typing
8+
from typing import *
9+
510
.. module:: typing
611
:synopsis: Support for type hints (see :pep:`484`).
712

@@ -261,19 +266,22 @@ Callable
261266
Frameworks expecting callback functions of specific signatures might be
262267
type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``.
263268

264-
For example::
269+
For example:
270+
271+
.. testcode::
265272

266273
from collections.abc import Callable
267274

268275
def feeder(get_next_item: Callable[[], str]) -> None:
269-
# Body
276+
... # Body
270277

271278
def async_query(on_success: Callable[[int], None],
272279
on_error: Callable[[int, Exception], None]) -> None:
273-
# Body
280+
... # Body
274281

275282
async def on_update(value: str) -> None:
276-
# Body
283+
... # Body
284+
277285
callback: Callable[[str], Awaitable[None]] = on_update
278286

279287
It is possible to declare the return type of a callable without specifying
@@ -431,11 +439,14 @@ In this case ``MyDict`` has a single parameter, ``T``.
431439

432440
Using a generic class without specifying type parameters assumes
433441
:data:`Any` for each position. In the following example, ``MyIterable`` is
434-
not generic but implicitly inherits from ``Iterable[Any]``::
442+
not generic but implicitly inherits from ``Iterable[Any]``:
443+
444+
.. testcode::
435445

436446
from collections.abc import Iterable
437447

438448
class MyIterable(Iterable): # Same as Iterable[Any]
449+
...
439450

440451
User-defined generic type aliases are also supported. Examples::
441452

@@ -701,9 +712,11 @@ These can be used as types in annotations and do not support ``[]``.
701712
A string created by composing ``LiteralString``-typed objects
702713
is also acceptable as a ``LiteralString``.
703714

704-
Example::
715+
Example:
716+
717+
.. testcode::
705718

706-
def run_query(sql: LiteralString) -> ...
719+
def run_query(sql: LiteralString) -> None:
707720
...
708721

709722
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
@@ -1596,16 +1609,19 @@ without the dedicated syntax, as documented below.
15961609
def __abs__(self) -> "Array[*Shape]": ...
15971610
def get_shape(self) -> tuple[*Shape]: ...
15981611

1599-
Type variable tuples can be happily combined with normal type variables::
1612+
Type variable tuples can be happily combined with normal type variables:
16001613

1601-
DType = TypeVar('DType')
1614+
.. testcode::
16021615

16031616
class Array[DType, *Shape]: # This is fine
16041617
pass
16051618
16061619
class Array2[*Shape, DType]: # This would also be fine
16071620
pass
16081621
1622+
class Height: ...
1623+
class Width: ...
1624+
16091625
float_array_1d: Array[float, Height] = Array() # Totally fine
16101626
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
16111627

@@ -1759,7 +1775,9 @@ without the dedicated syntax, as documented below.
17591775

17601776
The type of type aliases created through the :keyword:`type` statement.
17611777

1762-
Example::
1778+
Example:
1779+
1780+
.. doctest::
17631781

17641782
>>> type Alias = int
17651783
>>> type(Alias)
@@ -1769,7 +1787,9 @@ without the dedicated syntax, as documented below.
17691787

17701788
.. attribute:: __name__
17711789

1772-
The name of the type alias::
1790+
The name of the type alias:
1791+
1792+
.. doctest::
17731793

17741794
>>> type Alias = int
17751795
>>> Alias.__name__
@@ -2147,7 +2167,11 @@ These are not used in annotations. They are building blocks for declaring types.
21472167
group: list[T]
21482168

21492169
To create a generic ``TypedDict`` that is compatible with Python 3.11
2150-
or lower, inherit from :class:`Generic` explicitly::
2170+
or lower, inherit from :class:`Generic` explicitly:
2171+
2172+
.. testcode::
2173+
2174+
T = TypeVar("T")
21512175

21522176
class Group(TypedDict, Generic[T]):
21532177
key: T
@@ -2160,7 +2184,9 @@ These are not used in annotations. They are building blocks for declaring types.
21602184
.. attribute:: __total__
21612185

21622186
``Point2D.__total__`` gives the value of the ``total`` argument.
2163-
Example::
2187+
Example:
2188+
2189+
.. doctest::
21642190

21652191
>>> from typing import TypedDict
21662192
>>> class Point2D(TypedDict): pass
@@ -2190,7 +2216,9 @@ These are not used in annotations. They are building blocks for declaring types.
21902216
non-required keys in the same ``TypedDict`` . This is done by declaring a
21912217
``TypedDict`` with one value for the ``total`` argument and then
21922218
inheriting from it in another ``TypedDict`` with a different value for
2193-
``total``::
2219+
``total``:
2220+
2221+
.. doctest::
21942222

21952223
>>> class Point2D(TypedDict, total=False):
21962224
... x: int
@@ -2844,12 +2872,12 @@ Functions and decorators
28442872
decorated object performs runtime "magic" that
28452873
transforms a class, giving it :func:`dataclasses.dataclass`-like behaviors.
28462874

2847-
Example usage with a decorator function::
2875+
Example usage with a decorator function:
28482876

2849-
T = TypeVar("T")
2877+
.. testcode::
28502878

28512879
@dataclass_transform()
2852-
def create_model(cls: type[T]) -> type[T]:
2880+
def create_model[T](cls: type[T]) -> type[T]:
28532881
...
28542882
return cls
28552883

@@ -2953,7 +2981,9 @@ Functions and decorators
29532981
runtime but should be ignored by a type checker. At runtime, calling
29542982
a ``@overload``-decorated function directly will raise
29552983
:exc:`NotImplementedError`. An example of overload that gives a more
2956-
precise type than can be expressed using a union or a type variable::
2984+
precise type than can be expressed using a union or a type variable:
2985+
2986+
.. testcode::
29572987

29582988
@overload
29592989
def process(response: None) -> None:
@@ -2965,7 +2995,7 @@ Functions and decorators
29652995
def process(response: bytes) -> str:
29662996
...
29672997
def process(response):
2968-
<actual implementation>
2998+
... # actual implementation goes here
29692999

29703000
See :pep:`484` for more details and comparison with other typing semantics.
29713001

@@ -3057,10 +3087,13 @@ Functions and decorators
30573087
This helps prevent bugs that may occur when a base class is changed without
30583088
an equivalent change to a child class.
30593089

3060-
For example::
3090+
For example:
3091+
3092+
.. testcode::
30613093

30623094
class Base:
3063-
def log_status(self)
3095+
def log_status(self) -> None:
3096+
...
30643097

30653098
class Sub(Base):
30663099
@override
@@ -3119,14 +3152,16 @@ Introspection helpers
31193152

31203153
The function recursively replaces all ``Annotated[T, ...]`` with ``T``,
31213154
unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for
3122-
more information). For example::
3155+
more information). For example:
3156+
3157+
.. testcode::
31233158

31243159
class Student(NamedTuple):
31253160
name: Annotated[str, 'some marker']
31263161

3127-
get_type_hints(Student) == {'name': str}
3128-
get_type_hints(Student, include_extras=False) == {'name': str}
3129-
get_type_hints(Student, include_extras=True) == {
3162+
assert get_type_hints(Student) == {'name': str}
3163+
assert get_type_hints(Student, include_extras=False) == {'name': str}
3164+
assert get_type_hints(Student, include_extras=True) == {
31303165
'name': Annotated[str, 'some marker']
31313166
}
31323167

@@ -3153,7 +3188,9 @@ Introspection helpers
31533188
If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
31543189
return the underlying :class:`ParamSpec`.
31553190
Return ``None`` for unsupported objects.
3156-
Examples::
3191+
Examples:
3192+
3193+
.. testcode::
31573194

31583195
assert get_origin(str) is None
31593196
assert get_origin(Dict[str, int]) is dict
@@ -3172,7 +3209,9 @@ Introspection helpers
31723209
generic type, the order of ``(Y, Z, ...)`` may be different from the order
31733210
of the original arguments ``[Y, Z, ...]`` due to type caching.
31743211
Return ``()`` for unsupported objects.
3175-
Examples::
3212+
Examples:
3213+
3214+
.. testcode::
31763215

31773216
assert get_args(int) == ()
31783217
assert get_args(Dict[int, str]) == (int, str)
@@ -3184,14 +3223,20 @@ Introspection helpers
31843223

31853224
Check if a type is a :class:`TypedDict`.
31863225

3187-
For example::
3226+
For example:
3227+
3228+
.. testcode::
31883229

31893230
class Film(TypedDict):
31903231
title: str
31913232
year: int
31923233

3193-
is_typeddict(Film) # => True
3194-
is_typeddict(list | str) # => False
3234+
assert is_typeddict(Film)
3235+
assert not is_typeddict(list | str)
3236+
3237+
# TypedDict is a factory for creating typed dicts,
3238+
# not a typed dict itself
3239+
assert not is_typeddict(TypedDict)
31953240

31963241
.. versionadded:: 3.10
31973242

0 commit comments

Comments
 (0)
0