How to make pydantic raise a ValidationError if BaseModel get unexpected argument

Viewed 1347

I'm using pydantic to check the format of a parameter file. If there is a typo in the name of a parameter, I want pydantic to raise an error but it doesn't.

For example, the following does not raise any error:

from typing import Optional
from pydantic import BaseModel

class Param(BaseModel):
    param1: int
    param2: Optional[str] = None

p = Param(param1=2, parram2=9)

But parram2 is not defined in my BaseModel (because of the typo) so I would like pydantic to raise an error.

Any idea how I should do ?

Edit: I found a solution using dataclass instead of BaseModel but dataclass seems not to work with FastAPI so I can't use dataclass

1 Answers

I found the solution:

from typing import Optional
from pydantic import BaseModel
 

class Param(BaseModel):
    param1: int
    param2: Optional[str] = None

    class Config:
        extra = 'forbid'

p = Param(param1=2, param2=9)

The above now raise an error

Related