From the pydantic docs:
extra
whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore'
, 'allow'
, or
'forbid'
, or values of the Extra
enum (default: Extra.ignore
).
'forbid'
will cause validation to fail if extra attributes are
included, 'ignore'
will silently ignore any extra attributes, and
'allow'
will assign the attributes to the model.
This can either be included in the model Config
class, or as arguments when inheriting BaseModel
.
from pydantic import BaseModel, Extra
class BaseModel(BaseModel, extra=Extra.allow):
name: str
model = Model.parse_obj(
{"name": "Name", "address": "bla bla", "post": "post"}
)
print(model)
# name='Name' post='post' address='bla bla'
To get the extra values you could do something simple, like comparing the set of __fields__
defined on the class to the values in __dict__
on an instance:
class Model(BaseModel, extra=Extra.allow):
python_name: str = Field(alias="name")
@property
def extra_fields(self) -> set[str]:
return set(self.__dict__) - set(self.__fields__)
>>> Model.parse_obj({"name": "Name", "address": "bla bla", "post": "post"}).extra_fields
{'address', 'post'}
>>> Model.parse_obj({"name": "Name", "foobar": "fizz"}).extra_fields
{'foobar'}
>>> Model.parse_obj({"name": "Name"}).extra_fields
set()