Skip to content

Commit

Permalink
PEP 747: Minor fixes in code examples (#4193)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
sharkdp authored Jan 10, 2025
1 parent c67f3b5 commit 85f165e
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions peps/pep-0747.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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``
Expand All @@ -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``
Expand Down

0 comments on commit 85f165e

Please sign in to comment.