Home > Blockchain >  How to keep the attributes strictly to the properties of a pydantic class
How to keep the attributes strictly to the properties of a pydantic class

Time:03-08

For example, this is my class:

from pydantic import BaseModel

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

And here's a dictionary:

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

Now because height is not a property of the Config class, doing

d = Config(**data)

should throw an error but it doesn't. How can I make it throw an error if the dictionary isn't exactly what the class wants?

CodePudding user response:

Add this

from pydantic import Extra


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

The default is Extra.ignore.

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

  • Related