如何动态测试一个值是否符合Python字面类型?
我想了解如何动态测试一个值是否符合Python中的字面类型。假设我有以下代码:
from typing import Literal
PossibleValues = Literal["a", "b"]
x = input()
我想使用 isInstance
,但是这样做给了我一个类型:
>>> isinstance(x, PossibleValues)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../typing.py", line 720, in __instancecheck__
return self.__subclasscheck__(type(obj))
File "/.../typing.py", line 723, in __subclasscheck__
raise TypeError("Subscripted generics cannot be used with"
TypeError: Subscripted generics cannot be used with class and instance checks
我发现我可以使用 get_args
,但是这种方法似乎似乎有点骇客。
>>> from typing import get_args
>>> x = input()
'c'
>>> x in get_args(PossibleValues)
False
有更好的方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自在这里通过这样做的字面类型:
使用
typing.get_args
而不是__ args __ args __
可能更有Pythonic。我必须使用它来解决mypy错误,同时将文字存储到typealias
。From here I got the idea of testing if a string is of a literal type by doing this:
It is probably more pythonic to use
typing.get_args
instead of__args__
. I had to use that to get around mypy errors while storing the literal to aTypeAlias
.typing.get_args
在运行时完全可以接受,但这不会影响该类型Checker的类型(例如:Mypy和Pyright)。typeform
在 typeform 使用eNableExperimentionFeatures = true
( pr ):这将返回:
typing.get_args
is perfectly acceptable at runtime, but that won't affect the type that type checkers (eg: mypy and pyright) see.TypeForm
introduced in the draft of PEP 747 will allow us to narrow the type though, allowing the (narrowed) value to be used in other code expecting a value of the Literal's type. Pyright supportsTypeForm
when configured withenableExperimentalFeatures = true
(PR):This will return:
这是我刚刚想到,我对此感到非常满意。
(不可避免的)缺点是您需要为每种字面类型提出警卫功能。
Here is what I just came up with and I'm pretty happy with it.
The (inevitable) downside is that you will need to come up with the guard function for every literal type.
您可以尝试访问
__ args __
,但仍然不确定是否要明确调用魔术方法是一种方法。get_args
似乎是正确的选择。You can try to access
__args__
but still not sure if calling magic method explicitly is a way to go.get_args
seems to be the right option to go with.