Skip to content

Commit 2cfe778

Browse files
[3.12] Improve code examples in typing.rst (GH-105346) (#105422)
Improve code examples in `typing.rst` (GH-105346) (cherry picked from commit 81c8132) Co-authored-by: Alex Waygood <[email protected]>
1 parent a36fb69 commit 2cfe778

File tree

1 file changed

+75
-30
lines changed

1 file changed

+75
-30
lines changed

Doc/library/typing.rst

+75-30
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__
@@ -2158,7 +2178,11 @@ These are not used in annotations. They are building blocks for declaring types.
21582178
group: list[T]
21592179

21602180
To create a generic ``TypedDict`` that is compatible with Python 3.11
2161-
or lower, inherit from :class:`Generic` explicitly::
2181+
or lower, inherit from :class:`Generic` explicitly:
2182+
2183+
.. testcode::
2184+
2185+
T = TypeVar("T")
21622186

21632187
class Group(TypedDict, Generic[T]):
21642188
key: T
@@ -2171,7 +2195,9 @@ These are not used in annotations. They are building blocks for declaring types.
21712195
.. attribute:: __total__
21722196

21732197
``Point2D.__total__`` gives the value of the ``total`` argument.
2174-
Example::
2198+
Example:
2199+
2200+
.. doctest::
21752201

21762202
>>> from typing import TypedDict
21772203
>>> class Point2D(TypedDict): pass
@@ -2201,7 +2227,9 @@ These are not used in annotations. They are building blocks for declaring types.
22012227
non-required keys in the same ``TypedDict`` . This is done by declaring a
22022228
``TypedDict`` with one value for the ``total`` argument and then
22032229
inheriting from it in another ``TypedDict`` with a different value for
2204-
``total``::
2230+
``total``:
2231+
2232+
.. doctest::
22052233

22062234
>>> class Point2D(TypedDict, total=False):
22072235
... x: int
@@ -2860,12 +2888,12 @@ Functions and decorators
28602888
decorated object performs runtime "magic" that
28612889
transforms a class, giving it :func:`dataclasses.dataclass`-like behaviors.
28622890

2863-
Example usage with a decorator function::
2891+
Example usage with a decorator function:
28642892

2865-
T = TypeVar("T")
2893+
.. testcode::
28662894

28672895
@dataclass_transform()
2868-
def create_model(cls: type[T]) -> type[T]:
2896+
def create_model[T](cls: type[T]) -> type[T]:
28692897
...
28702898
return cls
28712899

@@ -2969,7 +2997,9 @@ Functions and decorators
29692997
runtime but should be ignored by a type checker. At runtime, calling
29702998
a ``@overload``-decorated function directly will raise
29712999
:exc:`NotImplementedError`. An example of overload that gives a more
2972-
precise type than can be expressed using a union or a type variable::
3000+
precise type than can be expressed using a union or a type variable:
3001+
3002+
.. testcode::
29733003

29743004
@overload
29753005
def process(response: None) -> None:
@@ -2981,7 +3011,7 @@ Functions and decorators
29813011
def process(response: bytes) -> str:
29823012
...
29833013
def process(response):
2984-
<actual implementation>
3014+
... # actual implementation goes here
29853015

29863016
See :pep:`484` for more details and comparison with other typing semantics.
29873017

@@ -3073,10 +3103,13 @@ Functions and decorators
30733103
This helps prevent bugs that may occur when a base class is changed without
30743104
an equivalent change to a child class.
30753105

3076-
For example::
3106+
For example:
3107+
3108+
.. testcode::
30773109

30783110
class Base:
3079-
def log_status(self)
3111+
def log_status(self) -> None:
3112+
...
30803113

30813114
class Sub(Base):
30823115
@override
@@ -3135,14 +3168,16 @@ Introspection helpers
31353168

31363169
The function recursively replaces all ``Annotated[T, ...]`` with ``T``,
31373170
unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for
3138-
more information). For example::
3171+
more information). For example:
3172+
3173+
.. testcode::
31393174

31403175
class Student(NamedTuple):
31413176
name: Annotated[str, 'some marker']
31423177

3143-
get_type_hints(Student) == {'name': str}
3144-
get_type_hints(Student, include_extras=False) == {'name': str}
3145-
get_type_hints(Student, include_extras=True) == {
3178+
assert get_type_hints(Student) == {'name': str}
3179+
assert get_type_hints(Student, include_extras=False) == {'name': str}
3180+
assert get_type_hints(Student, include_extras=True) == {
31463181
'name': Annotated[str, 'some marker']
31473182
}
31483183

@@ -3169,7 +3204,9 @@ Introspection helpers
31693204
If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
31703205
return the underlying :class:`ParamSpec`.
31713206
Return ``None`` for unsupported objects.
3172-
Examples::
3207+
Examples:
3208+
3209+
.. testcode::
31733210

31743211
assert get_origin(str) is None
31753212
assert get_origin(Dict[str, int]) is dict
@@ -3188,7 +3225,9 @@ Introspection helpers
31883225
generic type, the order of ``(Y, Z, ...)`` may be different from the order
31893226
of the original arguments ``[Y, Z, ...]`` due to type caching.
31903227
Return ``()`` for unsupported objects.
3191-
Examples::
3228+
Examples:
3229+
3230+
.. testcode::
31923231

31933232
assert get_args(int) == ()
31943233
assert get_args(Dict[int, str]) == (int, str)
@@ -3200,14 +3239,20 @@ Introspection helpers
32003239

32013240
Check if a type is a :class:`TypedDict`.
32023241

3203-
For example::
3242+
For example:
3243+
3244+
.. testcode::
32043245

32053246
class Film(TypedDict):
32063247
title: str
32073248
year: int
32083249

3209-
is_typeddict(Film) # => True
3210-
is_typeddict(list | str) # => False
3250+
assert is_typeddict(Film)
3251+
assert not is_typeddict(list | str)
3252+
3253+
# TypedDict is a factory for creating typed dicts,
3254+
# not a typed dict itself
3255+
assert not is_typeddict(TypedDict)
32113256

32123257
.. versionadded:: 3.10
32133258

0 commit comments

Comments
 (0)