泛型类型在 Stubgen 生成的 .pyi 文件中丢失其 Generic[T, ...] 基类

kwo*_*okt 6 python generics types mypy

假设有一个非常简单的类,它代表一个通用堆栈,因此继承自Generic[T]( \xc2\xa71 )。

\n
from typing import TypeVar, Generic, List\n\nT = TypeVar(\'T\')\n\nclass Stack(Generic[T]): #1\n    def __init__(self) -> None:\n        self.items: List[T] = []\n\n    def push(self, item: T) -> None:\n        self.items.append(item)\n\n    def pop(self) -> T:\n        return self.items.pop()\n\n    def empty(self) -> bool:\n        return not self.items\n
Run Code Online (Sandbox Code Playgroud)\n

然后让我们.pyi为该类所在的模块生成一个存根文件Stack,例如stack.py

\n
$ stubgen stack.py --output stubs\n
Run Code Online (Sandbox Code Playgroud)\n

很明显,Generic[T]基类被意外剥离(\xc2\xa72)。同时,该items属性的类型提示被替换为Any\xc2\xa73)。push此外,让事情变得更奇怪的是,和的存根版本仍然分别具有参数和返回值的pop类型提示( \xc2\xa74\xc2\xa75)。T

\n
from typing import Any, TypeVar\n\nT = TypeVar(\'T\')\n\nclass Stack: #2\n    items: Any = ... #3\n    def __init__(self) -> None: ...\n    def push(self, item: T) -> None: ... #4\n    def pop(self) -> T: ... #5\n    def empty(self) -> bool: ...\n
Run Code Online (Sandbox Code Playgroud)\n

存根生成期间发生了什么?有什么解释可以证明这种行为的合理性吗?

\n

PS我的mypy版本是0.790。

\n