pydantic "ImportError: cannot import name 'BaseSettings'" (pydantic-settings) in CI
In pydantic v2, BaseSettings was moved out of the core package into pydantic-settings. Code that still does from pydantic import BaseSettings raises an ImportError once v2 is installed.
What this error means
Startup fails with "ImportError: cannot import name 'BaseSettings' from 'pydantic'" after pydantic resolved to v2.
python
ImportError: cannot import name 'BaseSettings' from 'pydantic'
(/opt/venv/lib/python3.12/site-packages/pydantic/__init__.py)Common causes
BaseSettings moved to pydantic-settings in v2
The class is no longer exported from pydantic; it now lives in the pydantic-settings distribution.
The new package is not installed
Code imports from pydantic_settings, but the pydantic-settings dependency was never added to requirements.
How to fix it
Install pydantic-settings and update imports
- Add
pydantic-settingsto requirements. - Import
BaseSettingsfrompydantic_settingsinstead ofpydantic. - Move
SettingsConfigDictusage as needed.
python
# pip install pydantic-settings
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
database_url: str
model_config = SettingsConfigDict(env_file=".env")Or pin pydantic to v1 temporarily
If you are not ready to split the package, pin v1 where BaseSettings is still in core.
Terminal
pip install "pydantic<2"How to prevent it
- Add pydantic-settings when you move to pydantic v2.
- Pin pydantic so the move is intentional.
- Grep for
from pydantic import BaseSettingsbefore upgrading.
Related guides
pydantic "PydanticUserError" from v1 vs v2 validator API in CIFix pydantic "PydanticUserError" after upgrading to v2 in CI - v1 patterns like @validator, Config classes, o…
FastAPI "RequestValidationError" / pydantic 422 on request body in CIFix FastAPI tests failing with a 422 and pydantic "ValidationError" on the request body in CI - the test payl…
Django REST Framework "ModuleNotFoundError: No module named 'rest_framework'" in CIFix Django REST Framework "ModuleNotFoundError: No module named 'rest_framework'" in CI - djangorestframework…