Replies: 2 comments 2 replies
-
The expression The rest of the code looks fine and is an appropriate use of PEP 747. To cover all possible cases, your implementation of |
Beta Was this translation helpful? Give feedback.
-
In addition to listing Literal values, I've wanted a way check if a given value is a valid member (rather than using Enums) and landed on this: from __future__ import annotations # Required as TypeForm is not yet released in typing_extensions
from typing import TYPE_CHECKING, Literal, TypeAliasType, TypeIs, assert_type, get_args, get_origin
if TYPE_CHECKING: # Required as TypeForm is not yet released in typing_extensions
from typing_extensions import TypeForm
type PossibleValues = Literal["a", "b"]
def is_literal_value[T](value: object, typx: TypeForm[T]) -> TypeIs[T]:
if isinstance(typx, TypeAliasType):
typx = typx.__value__
if get_origin(typx) is Literal:
return value in get_args(typx)
return False
def check(x: str):
if is_literal_value(x, PossibleValues):
assert_type(x, PossibleValues)
print(f"{x} is in PossibleValues")
else:
assert_type(x, str)
print(f"{x} is not in PossibleValues")
check("a")
check("z") |
Beta Was this translation helpful? Give feedback.
-
Sometimes I need to iterate over
Literal
values and for such cases I tend to useget_args
, which revealed type istuple[Any, ...]
.In those moment I wished I had type safe
Literal
value extraction possible, but it wasn't: boundingTypeVar
withLiteral
isn't allowed as well wrappingtype
around such «generic literal».So, when PEP 747 became provisionally supported in Pyright I started playing around with it and realized it's actually possible to achieve what I want for
Literal
types: it's hacky but still.See the code in Pyright playground or the code snippet provided below.
Note that ellipsis inside
Literal
is crucial, nothing works without it.Is this Pyright «bug»? Should such behavior—very handy I'd say 🙂— be allowed?
Beta Was this translation helpful? Give feedback.
All reactions