我想定义一种“包装器”通用类型,例如
MyType[T]
,以便它具有与包装类型相同的类型接口。
from typing import Generic, TypeVar
T = TypeVar("T")
class MyType(Generic):
pass # what to write here?
因此,举个例子,当我有一个类型
MyType[int]
时,类型检查器应该将其视为 int
类型。
这可能吗?如果是的话,怎么办?
我可能错过了你正在寻找的核心内容。如果是这样,我很乐意修改这个答案,但是如果您希望对新类型进行与其基本类型相同的类型检查,请考虑:
MyType = int
a: MyType = 1
运行
b = a + 1
不会产生 linting 错误,但 c = a + "a"
应发出警告。某种程度上:Operator "+" not supported for types "Literal[1]" and "Literal['a']"
我不确定是否需要创建一个全新的泛型类,如果您希望新类型的行为就像
int
(在本例中)