8000 Prevent `BaseModel` class from being instantiated · Issue #1674 · pydantic/pydantic-core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Prevent BaseModel class from being instantiated #1674
Open
@Viicos

Description

@Viicos

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)).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0