定义与“typing.get_type_hints()”一起使用的自定义类型
Defining a custom type that works with `typing.get_type_hints()`
我想使用一个类型提示,它是一个具有某种结构的对象,如下所示:
import typing
class MyType:
def __init__(self, param):
self.param = param
def func(a: MyType(1)):
pass
print(typing.get_type_hints(func))
这运行良好,生产
{'a': <__main__.MyType object at 0x107a3c110>}
但如果有人添加
from __future__ import annotations
在代码的开头,模仿 Python 3.8+ 的默认行为(将注释转换为在 get_type_hints()
中计算的字符串),它会产生错误
TypeError: Forward references must evaluate to types. Got <__main__.MyType object at 0x10f4ff0d0>
是否可以使用新的注释行为使其工作?据我所知,我需要 subclass MyType
使其对象类型自己,但我无法弄清楚我应该使用哪个基础 class。
typing.get_type_hints()
将尝试将任何可能 forward references 的注释转换为类型。
在您的示例中,a
的注释不是 type
的子类,因为它是 MyType
的 实例 。 MyType
本身 是 type
的子类。
也许你的代码就是这样说的?在大多数情况下,使用类型的实例注释您的函数没有多大意义。
def func(a: MyType):
pass
似乎一种可能的方法是创建元类:
class MyType(type):
def __new__(cls, param):
return super().__new__(cls, f'MyType({param})', (MyType,), {})
def __init__(self, param):
self.param = param
这满足get_type_hints()
。
typing
定义了自己的元类,但它们都标记为私有且没有文档记录,所以最好不要碰它们。
我想使用一个类型提示,它是一个具有某种结构的对象,如下所示:
import typing
class MyType:
def __init__(self, param):
self.param = param
def func(a: MyType(1)):
pass
print(typing.get_type_hints(func))
这运行良好,生产
{'a': <__main__.MyType object at 0x107a3c110>}
但如果有人添加
from __future__ import annotations
在代码的开头,模仿 Python 3.8+ 的默认行为(将注释转换为在 get_type_hints()
中计算的字符串),它会产生错误
TypeError: Forward references must evaluate to types. Got <__main__.MyType object at 0x10f4ff0d0>
是否可以使用新的注释行为使其工作?据我所知,我需要 subclass MyType
使其对象类型自己,但我无法弄清楚我应该使用哪个基础 class。
typing.get_type_hints()
将尝试将任何可能 forward references 的注释转换为类型。
在您的示例中,a
的注释不是 type
的子类,因为它是 MyType
的 实例 。 MyType
本身 是 type
的子类。
也许你的代码就是这样说的?在大多数情况下,使用类型的实例注释您的函数没有多大意义。
def func(a: MyType):
pass
似乎一种可能的方法是创建元类:
class MyType(type):
def __new__(cls, param):
return super().__new__(cls, f'MyType({param})', (MyType,), {})
def __init__(self, param):
self.param = param
这满足get_type_hints()
。
typing
定义了自己的元类,但它们都标记为私有且没有文档记录,所以最好不要碰它们。