ImportError: cannot import name 'ModelMetaclass' from 'pydantic.main'
Fixes ImportError: cannot import name 'ModelMetaclass' from 'pydantic.main' Use when v2 code importing ModelMetaclass from pydantic.main Not for: normal BaseModel subclassing (you never need the metaclass)
How to fix ImportError: cannot import name 'ModelMetaclass' from 'pydantic.main'
ModelMetaclass is not public API in v2. If you just need a model's metaclass, use type(YourModel) instead of importing it. If a library does this (motor-odm did), upgrade the library. The class does exist at pydantic._internal._model_construction, but that is private and can move between releases.
The exact error
ImportError: cannot import name 'ModelMetaclass' from 'pydantic.main'Fix it
- Replace
from pydantic.main import ModelMetaclassusage:type(MyModel)gives you the metaclass.
Expected: no import needed
- If a library does this (motor-odm did), upgrade the library.
Expected: fixed upstream
- Last resort: import from
pydantic._internal._model_construction.
Expected: works but pinned to internals
When this applies
v2 code importing ModelMetaclass from pydantic.main
When this does NOT apply
normal BaseModel subclassing (you never need the metaclass)
Versions
pydantic v2
Why it happens
v2 rebuilt the internals; ModelMetaclass left the public namespace.
Edge cases
Depending on _internal ties you to exact pydantic versions; avoid in libraries.