我有一个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)
我正在尝试使用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 object to be put once only.
Objects are considered identical if hash(object) are identical.
"""
def __init__(self, maxsize: int=0) -> None:
"""Initialise queue with maximum number of items.
0 for infinite queue
"""
super().__init__(maxsize)
self.all_items = set() # type: Set[T]
def _put(self, item: T) -> None:
if item not in self.all_items:
super()._put(item)
self.all_items.add(item)
mypy 在类定义行上抛出一个警告,说“缺少泛型类型的类型参数”。
我认为我需要一个Generic[T]
地方,但我所做的每一次尝试都会引发语法错误。文档中的所有示例都显示了从任何其他对象继承Generic[T]
但不从任何其他对象继承。
有谁知道如何定义 SetQueue 的泛型类型?