Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PEP 747: Minor fixes in code examples #4193

Merged
merged 1 commit into from
Jan 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading