Python 中是否有参数化自定义类型的方法?
Is there a way of parametrizing custom types in Python?
是否有任何方法可以参数化使用 NewType
创建的新类型,类似于如何使用下标对 typing.Sequence
等进行参数化?或者通过不同的方式达到类似的结果?
下面的示例说明了我 喜欢 做的事情,但是它因 TypeError: 'function' object is not subscriptable
而失败,因为 NewType
returns 一个函数。
from typing import NewType, Sequence, TypeVar
T = TypeVar("T")
Type1 = NewType("Type1", float)
Type2 = NewType("Type2", Sequence[T])
Works = Sequence[Type1]
Fails = Type2[Type1]
我希望这样做的原因是我正在创建一个数据类,在 __post_init__
中,我想 运行 一些特定的逻辑,具体取决于属性的类型。
Type1
和 Type2
是不可订阅的 function
类型。即使您在 Type2
上手动实现 __getitem__
(方括号 [] 运算符的内置函数),python 也会引发 TypeError。
如果你真的想在你的类型上使用方括号,我建议创建一个 class 并实现 __getitem__
和 __setitem__
.
下面是 class 的一个简单示例:
class Foo:
def __init__(self):
self.__type_lookup = {}
def __getitem__(self, key):
return self.__type_lookup[key]
def __setitem__(self, key, value):
self.__type_lookup[key] = value
我在 Mypy 文档的 generics 部分找到了解决方案:从 typing
模块中继承适当的类型。 (而不是尝试使用 NewType
。)例如,
from typing import NewType, Sequence
Type1 = NewType("Type1", float)
class Type2(Sequence):
pass
Works = Type2[Type1]
是否有任何方法可以参数化使用 NewType
创建的新类型,类似于如何使用下标对 typing.Sequence
等进行参数化?或者通过不同的方式达到类似的结果?
下面的示例说明了我 喜欢 做的事情,但是它因 TypeError: 'function' object is not subscriptable
而失败,因为 NewType
returns 一个函数。
from typing import NewType, Sequence, TypeVar
T = TypeVar("T")
Type1 = NewType("Type1", float)
Type2 = NewType("Type2", Sequence[T])
Works = Sequence[Type1]
Fails = Type2[Type1]
我希望这样做的原因是我正在创建一个数据类,在 __post_init__
中,我想 运行 一些特定的逻辑,具体取决于属性的类型。
Type1
和 Type2
是不可订阅的 function
类型。即使您在 Type2
上手动实现 __getitem__
(方括号 [] 运算符的内置函数),python 也会引发 TypeError。
如果你真的想在你的类型上使用方括号,我建议创建一个 class 并实现 __getitem__
和 __setitem__
.
下面是 class 的一个简单示例:
class Foo:
def __init__(self):
self.__type_lookup = {}
def __getitem__(self, key):
return self.__type_lookup[key]
def __setitem__(self, key, value):
self.__type_lookup[key] = value
我在 Mypy 文档的 generics 部分找到了解决方案:从 typing
模块中继承适当的类型。 (而不是尝试使用 NewType
。)例如,
from typing import NewType, Sequence
Type1 = NewType("Type1", float)
class Type2(Sequence):
pass
Works = Type2[Type1]