Hey,
First of all, thanks for the awesome work you've done with Pydantic. We have been slowly adopting Pydantic on all our projects across my team and loving it so far.
Our biggest issue so far is that we couldn't find a simple way to throw an error when erroneous keywords are passed into the BaseModel __init__ . When working with project with very large and nested configurations it is extremely easy to make a typo when creating this configuration and this error gets silently ignored.
Is there any simple way of doing this that I am unaware of?
pydantic version: 1.4
pydantic compiled: False
install path: /Users/miguelvera/env/miniconda2/envs/mirta/lib/python3.7/site-packages/pydantic
python version: 3.7.8 | packaged by conda-forge | (default, Jul 23 2020, 03:39:37) [Clang 10.0.0 ]
platform: Darwin-19.4.0-x86_64-i386-64bit
optional deps. installed: ['typing-extensions']
Small example:
import pydantic
class Configuration(BaseModel):
input: FilePath = 'input'
output: FilePath = 'output'
if __name__ == '__main__':
args_dict = {
"input" : '/mnt/mypath/inputs',
"outptu" : '/myotherpath/output',
}
# How can I make this throw an error for receiving a keyword that does not exist? (outptu)
Configuration(**args_dict)
Thanks in advance!
There is a model config Option called extra. By default is is set to 'ignore', but you can set it to 'forbid' to throw a validation error when an unknown attribute is included.
Would this suffice for your use case?
@philipp-sontag-by is right.
from pydantic import BaseModel, Extra, FilePath
class Configuration(BaseModel):
input: FilePath = 'input'
output: FilePath = 'output'
class Config:
extra = Extra.forbid # or just 'forbid'
and you will have a validation error
pydantic.error_wrappers.ValidationError: 1 validation error for Configuration
outptu
extra fields not permitted (type=value_error.extra)
Sorry for the late response.
This is exactly what I was looking for, thanks!
Most helpful comment
There is a model config Option called extra. By default is is set to 'ignore', but you can set it to 'forbid' to throw a validation error when an unknown attribute is included.
Would this suffice for your use case?