动态创建类时如何在字段上设置类型提示

Ste*_*veJ 4 python pydantic

由于超出这个问题范围的原因,我想创建一个动态的 Python-Pydantic 类。我很接近,但不知道如何添加类型提示。

鉴于:

class MyClass(BaseModel):

    class Config:
        extra = Extra.allow

        schema_extra = {
            '$id': "http://my-site.com/production.json",
            '$schema': "https://json-schema.org/draft/2020-12/schema",
            'title': 'pattern="^.+-.*"'
        }


if __name__ == '__main__':

    cls = type('A', (MyClass,), {'__doc__': 'class created by type', 'my_field': Field("test", type='int')})
    p = cls()
    schema = p.schema()
    pprint(schema)
Run Code Online (Sandbox Code Playgroud)

我明白了:

{'$id': 'http://my-site.com/production.json',
 '$schema': 'https://json-schema.org/draft/2020-12/schema',
 'description': 'class created by type',
 'properties': {'my_field': {'default': 'test',
                             'title': 'My Field',
                             'type': 'string'}},
 'title': 'pattern="^.+-.*"',
 'type': 'object'}
Run Code Online (Sandbox Code Playgroud)

我希望“ properties -> myfield -> type ”为int而不是string

rv.*_*tch 6

创建一个__annotations__dict 对象并在其中添加类型定义。当您定义它时,这与转换的映射相同my_field: int = Field('test')

注意:在下面,我只显示了添加/修改的代码部分。

    cls_annotations = {'my_field': int} ## Added

    cls = type('A', (MyClass,), {'__doc__': 'class created by type',
                                 ## Added
                                 '__annotations__': cls_annotations,
                                 ##
                                 'my_field': Field("test")})
Run Code Online (Sandbox Code Playgroud)

输出:

...
 'properties': {'my_field': {'default': 'test',
                             'title': 'My Field',
                             'type': 'integer'}},
...
Run Code Online (Sandbox Code Playgroud)