如何在Python中动态创建类型注释?

问题描述 投票:0回答:1

通常,可以定义一个带有一些类型注释字段的类,如下所示:

class A:
    a: str

如何使用

type
函数动态执行此操作?

我知道将

a
分配给一个值时的情况,即,在

的情况下
class B:
    a = 'hello world'

我们可以

B = type('B', (), {'a': 'hello world'})

但是,我不知道如何动态地将类型注释信息添加到

type
函数中。

对于上下文,我们有一些函数可以将此类信息读取到 codegen 测试和 api 调用。

python metaprogramming
1个回答
0
投票

正如@jonrsharpe建议的那样,我们可以直接修改类的

__annotations__
。我的理解是这样的:

class C:
    ...

C.__annotations__['a'] = str

这回答了问题。

© www.soinside.com 2019 - 2024. All rights reserved.