相关疑难解决方法(0)

mypy:如何定义通用子类

我有一个queue.Queue像这样的子类:

class SetQueue(queue.Queue):
    """Queue which will allow a given object to be put once only.

    Objects are considered identical if hash(object) are identical.
    """

    def __init__(self, maxsize=0):
        """Initialise queue with maximum number of items.

        0 for infinite queue
        """
        super().__init__(maxsize)
        self.all_items = set()

    def _put(self):
        if item not in self.all_items:
            super()._put(item)
            self.all_items.add(item)
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用mypy进行静态类型检查。在这种情况下,SetQueue应该采用通用对象T。这是我到目前为止的尝试:

from typing import Generic, Iterable, Set, TypeVar

# Type for mypy generics
T = TypeVar('T')

class SetQueue(queue.Queue):
    """Queue which will allow a given …
Run Code Online (Sandbox Code Playgroud)

python types mypy

3
推荐指数
2
解决办法
1478
查看次数

标签 统计

mypy ×1

python ×1

types ×1