在 Python3.6(特别是对于 PyCharm)中输入提示同构队列的正确方法是什么? [英] What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?
问题描述
我正在用 Python 3.6 编写一个分形生成器,我使用 multiprocessing.Queue
s 将消息从主线程传递给工作线程.这是我迄今为止尝试过的,但 PyCharm 似乎无法推断从队列中取出的项目的属性类型:
I'm writing a fractal generator in Python 3.6, and I use multiprocessing.Queue
s to pass messages from the main thread to the workers. This is what I've tried so far, but PyCharm doesn't seem to be able to infer attribute types for items taken from the queues:
from typing import NamedTuple, Any, Generic, TypeVar, Tuple
from multiprocessing import Process, Queue
T = TypeVar()
class Message(NamedTuple):
method: str
id: str
data: Any = None
class TypedQueue(Generic[T]):
def get(self) -> T:
...
def put(self, m: T) -> None:
...
MessageQ = TypedQueue[Message]
class FractalWorker(Process):
def __init__(self, work: MessageQ, results: MessageQ)
super().__init__()
self.work = work
self.results = results
@staticmethod
def make_queues() -> Tuple[MessageQ, MessageQ]:
work = cast(MessageQ, Queue())
results = cast(MessageQ, Queue())
return work, results
我希望 PyCharm 能够告诉 self.work.get
结果的属性具有由 Message
类指定的类型.我也想知道是否有类似这样的类型提示队列的标准方法.
I want PyCharm to be able to tell that the attributes of the result of self.work.get
have the types specified by the Message
class. I also want to know if there is a standard way of type hinting Queues similar to this.
推荐答案
TypeVar
应该有一个名字.
T = TypeVar("T")
解决了这个问题.
这篇关于在 Python3.6(特别是对于 PyCharm)中输入提示同构队列的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!