pydantic-core
pydantic-core copied to clipboard
Prevent `BaseModel` class from being instantiated
In Pydantic, we prevent direct BaseModel instantiation:
BaseModel()
#> pydantic.errors.PydanticUserError: Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly
However, as pydantic-core uses __new__ to create model instances, the following will unexpectedly work:
from pydantic import BaseModel
class Model(BaseModel):
f: BaseModel
m = Model.model_validate({'f': {}})
# m is successfully created. However, because `m.f` is an instance of `BaseModel`, it blows up e.g. when printing the instance
print(m)
#> AttributeError: 'BaseModel' object has no attribute '__private_attributes__'. Did you mean: '__static_attributes__'?
I'm not sure if a validation error should be used or a different exception (ValueError?), but we should raise something and add hints about why this is happening (most of the time, users expected some BaseModel subclass to actually be used but this isn't possible when validating from an arbitrary mapping — see https://github.com/pydantic/pydantic/issues/11597#issuecomment-2743067947).
Is this still worked on?