[英]How can I type hint a variable whose Union type gets narrowed in Python?
[英]Can I type hint a subset of a Union in Python?
我想要一个生产者可以在运行时注册的异构队列。 这将用于 Elm 风格的 tui 系统。 因此,库可以为用户、hhtp 请求等提供各种注册功能。问题是,这些功能的签名应该是什么?
我希望用户能够向类型系统声明他们想要处理什么样的事件: Queue[Union[...]]
,而且还有注册函数来接受any queue which has T as a Union member
。 可以表达吗?
from queue import Queue
from typing import Union
def register_str_source(queue: "Queue[str]"): ...
def register_int_source(queue: "Queue[int]"): ...
queue: "Queue[Union[str, int]]" = Queue()
# Argument 1 to "register_str_source" has incompatible type "Queue[Union[str, int]]"; expected "Queue[str]"
register_str_source(queue)
# Argument 1 to "register_int_source" has incompatible type "Queue[Union[str, int]]"; expected "Queue[int]"
register_int_source(queue)
while event := queue.get(): # Exhaustive types are desirable here
if isinstance(event, str):
print(event) # One may choose to register to additional events when handling this one
elif isinstance(event, int):
print(event)
我试过了:
Union[str, ...]
。 这是无效的register_*
函数中使用裸Queue
。 这不会在Queue.put
中捕获错误类型的 Queue.put。TypeVar
和Protocol
吗?您可以使用包装队列的逆变通用 class 来执行此操作。
https://mypy.readthedocs.io/en/stable/generics.html#variance-of-generic-types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.