From 0f8a511c3f1f2c0b9f69e1f6520bf7c9f5ee271c Mon Sep 17 00:00:00 2001 From: David Peter Date: Wed, 8 Jan 2025 10:55:42 +0100 Subject: [PATCH] PEP 747: Minor fixes in code examples - 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 --- peps/pep-0747.rst | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/peps/pep-0747.rst b/peps/pep-0747.rst index 1d5483ad77d..08fd44ae52b 100644 --- a/peps/pep-0747.rst +++ b/peps/pep-0747.rst @@ -410,8 +410,9 @@ extract components of some type form objects. :: import typing + from typing import TypeForm, cast - def strip_annotated_metadata(typx: TypeForm[T]) -> TypeForm[T]: + def strip_annotated_metadata[T](typx: TypeForm[T]) -> TypeForm[T]: if typing.get_origin(typx) is typing.Annotated: typx = cast(TypeForm[T], typing.get_args(typx)[0]) return typx @@ -423,15 +424,16 @@ kinds of type form objects: import types import typing + from typing import TypeForm, cast def split_union(typx: TypeForm) -> tuple[TypeForm, ...]: - if isinstance(typ, types.UnionType): # X | Y - return cast(tuple[TypeForm, ...], typing.get_args(typ)) - if typing.get_origin(typ) is typing.Union: # Union[X, Y] - return cast(tuple[TypeForm, ...], typing.get_args(typ)) - if typ in (typing.Never, typing.NoReturn,): + if isinstance(typx, types.UnionType): # X | Y + return cast(tuple[TypeForm, ...], typing.get_args(typx)) + if typing.get_origin(typx) is typing.Union: # Union[X, Y] + return cast(tuple[TypeForm, ...], typing.get_args(typx)) + if typx in (typing.Never, typing.NoReturn,): return () - return (typ,) + return (typx,) Combining with a type variable @@ -443,7 +445,7 @@ within the same function definition: :: def as_instance[T](typx: TypeForm[T]) -> T | None: - return typ() if isinstance(typ, type) else None + return typx() if isinstance(typx, type) else None Combining with ``type`` @@ -455,7 +457,7 @@ variable within the same function definition: :: def as_type[T](typx: TypeForm[T]) -> type[T] | None: - return typ if isinstance(typ, type) else None + return typx if isinstance(typx, type) else None Combining with ``TypeIs`` and ``TypeGuard``