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

How to set type hint on field when dynamically creating a class

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

给定:

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)

我明白了:

{'$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'}

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

创建一个 __annotations__ dict 对象并在其中添加您的类型定义。当您将其定义为 my_field: int = Field('test').

时,这与被翻译的映射相同

Note: in below, I only show the parts of the code that were added / modified.

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

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

输出:

...
 'properties': {'my_field': {'default': 'test',
                             'title': 'My Field',
                             'type': 'integer'}},
...