kwo*_*okt 6 python generics types mypy
假设有一个非常简单的类,它代表一个通用堆栈,因此继承自Generic[T]( \xc2\xa71 )。
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\nRun Code Online (Sandbox Code Playgroud)\n然后让我们.pyi为该类所在的模块生成一个存根文件Stack,例如stack.py:
$ stubgen stack.py --output stubs\nRun Code Online (Sandbox Code Playgroud)\n很明显,Generic[T]基类被意外剥离(\xc2\xa72)。同时,该items属性的类型提示被替换为Any(\xc2\xa73)。push此外,让事情变得更奇怪的是,和的存根版本仍然分别具有参数和返回值的pop类型提示( \xc2\xa74和\xc2\xa75)。T
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: ...\nRun Code Online (Sandbox Code Playgroud)\n存根生成期间发生了什么?有什么解释可以证明这种行为的合理性吗?
\nPS我的mypy版本是0.790。