Skip to content

Prevent BaseModel class from being instantiated #1674

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Viicos opened this issue Mar 21, 2025 · 0 comments
Open

Prevent BaseModel class from being instantiated #1674

Viicos opened this issue Mar 21, 2025 · 0 comments

Comments

@Viicos
Copy link
Member

Viicos commented Mar 21, 2025

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 pydantic/pydantic#11597 (comment)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant