如何将属性严格保持为 pydantic class 的属性

How to keep the attributes strictly to the properties of a pydantic class

例如,这是我的 class:

from pydantic import BaseModel

class Config(BaseModel):
    name: str
    age: int

这是一本字典:

data = {"name": "XYZ", "age": 18, "height": "180cm"}

现在因为 height 不是 Config class 的 属性,正在做

d = Config(**data)

应该抛出一个错误,但它没有。如果字典不是 class 想要的,我怎样才能让它抛出错误?

添加这个

from pydantic import Extra


class Config(BaseModel, extra=Extra.forbid):
    ...

默认为Extra.ignore

https://pydantic-docs.helpmanual.io/usage/model_config/