What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?

大憨熊 提交于 2020-01-14 08:27:38

问题


I'm writing a fractal generator in Python 3.6, and I use multiprocessing.Queues 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

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.


回答1:


TypeVar should have a name.

T = TypeVar("T") fixes the problem.




回答2:


Old Question, but I just found

P: "Queue[Path]" = Queue()

to work with both queue.Queue and multiprocessing.Queue in PyCharm



来源:https://stackoverflow.com/questions/48956422/what-is-the-correct-way-to-type-hint-a-homogenous-queue-in-python3-6-especially

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!