Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 737
cylon86 Avatar asked Oct 23 '25 09:10

cylon86


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

like image 133
cylon86 Avatar answered Oct 25 '25 23:10

cylon86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!