【问题标题】:What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?在 Python3.6 中键入提示同质队列的正确方法是什么(尤其是对于 PyCharm)?
【发布时间】:2018-08-04 00:22:40
【问题描述】:

我正在 Python 3.6 中编写分形生成器,并使用 multiprocessing.Queues 将消息从主线程传递给工作线程。这是我迄今为止尝试过的,但 PyCharm 似乎无法推断从队列中获取的项目的属性类型:

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 类指定的类型。我也想知道是否有类似于此的类型提示队列的标准方法。

【问题讨论】:

    标签: pycharm python-3.6 type-hinting mypy


    【解决方案1】:

    老问题,但我刚刚发现

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

    在 PyCharm 中同时使用 queue.Queuemultiprocessing.Queue

    【讨论】:

    • Path 应该是TypeVar 这里的@Xtrem532 吗?还是别的什么?
    • iirc 这是一个名为 P 的队列,其中包含 pathlib.Path 对象
    【解决方案2】:

    TypeVar 应该有一个名字。

    T = TypeVar("T") 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2020-08-31
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2023-04-09
      • 2014-02-03
      相关资源
      最近更新 更多