Skip to content

Commit 85f165e

Browse files
authored
PEP 747: Minor fixes in code examples (#4193)
- Added missing generic parameter for `strip_annotated_metadata` - Use the correct `typx` parameter name for `TypeForm` arguments in the `split_union` and `as_instance` / `as_type` examples. - Add `from typing import TypeForm, cast` imports to make the usage of `typing` symbols consistent
1 parent c67f3b5 commit 85f165e

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

peps/pep-0747.rst

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -410,8 +410,9 @@ extract components of some type form objects.
410410
::
411411

412412
import typing
413+
from typing import TypeForm, cast
413414

414-
def strip_annotated_metadata(typx: TypeForm[T]) -> TypeForm[T]:
415+
def strip_annotated_metadata[T](typx: TypeForm[T]) -> TypeForm[T]:
415416
if typing.get_origin(typx) is typing.Annotated:
416417
typx = cast(TypeForm[T], typing.get_args(typx)[0])
417418
return typx
@@ -423,15 +424,16 @@ kinds of type form objects:
423424

424425
import types
425426
import typing
427+
from typing import TypeForm, cast
426428

427429
def split_union(typx: TypeForm) -> tuple[TypeForm, ...]:
428-
if isinstance(typ, types.UnionType): # X | Y
429-
return cast(tuple[TypeForm, ...], typing.get_args(typ))
430-
if typing.get_origin(typ) is typing.Union: # Union[X, Y]
431-
return cast(tuple[TypeForm, ...], typing.get_args(typ))
432-
if typ in (typing.Never, typing.NoReturn,):
430+
if isinstance(typx, types.UnionType): # X | Y
431+
return cast(tuple[TypeForm, ...], typing.get_args(typx))
432+
if typing.get_origin(typx) is typing.Union: # Union[X, Y]
433+
return cast(tuple[TypeForm, ...], typing.get_args(typx))
434+
if typx in (typing.Never, typing.NoReturn,):
433435
return ()
434-
return (typ,)
436+
return (typx,)
435437

436438

437439
Combining with a type variable
@@ -443,7 +445,7 @@ within the same function definition:
443445
::
444446

445447
def as_instance[T](typx: TypeForm[T]) -> T | None:
446-
return typ() if isinstance(typ, type) else None
448+
return typx() if isinstance(typx, type) else None
447449

448450

449451
Combining with ``type``
@@ -455,7 +457,7 @@ variable within the same function definition:
455457
::
456458

457459
def as_type[T](typx: TypeForm[T]) -> type[T] | None:
458-
return typ if isinstance(typ, type) else None
460+
return typx if isinstance(typx, type) else None
459461

460462

461463
Combining with ``TypeIs`` and ``TypeGuard``

0 commit comments

Comments
 (0)