ImportError 🐍 Python

ImportError: cannot import name 'x' from 'y'

The module was found, but the name you’re importing from it doesn’t exist — usually a version change or a circular import.

Seen on: Python

Meaning

Python loaded the module but the attribute isn’t there. Libraries rename/move things across versions; “(most likely due to a circular import)” in the message means two modules import each other at load time.

Common causes

  • Library version changed/removed the name
  • Circular import between your modules
  • Typo or wrong module path
  • Local file shadowing the real module

⚡ Quick fix

  1. Check the installed version (pip show pkg) and its docs/changelog
  2. Pin a compatible version in requirements.txt
  3. Break circular imports by moving the import inside the function or into a third module

Detailed fix by platform

Python

  1. For circular imports, import the module (import app.models as models) rather than names, or restructure shared code.

Code examples

Circular import and the fix

python
# models.py
from services import send_welcome      # ← imports services at load time
class User: ...

# services.py
from models import User                # ← ImportError: cannot import name 'User' (circular import)
def send_welcome(user: "User"): ...

# ✅ services.py — import inside the function (or move shared code to a third module)
def send_welcome(user):
    from models import User
    ...

Check the installed version exports the name

bash
python -m pip show pydantic
python -c "import pydantic, inspect; print(pydantic.__version__, hasattr(pydantic, 'BaseSettings'))"

Example: BaseSettings moved out of pydantic in v2 (now pydantic_settings).

How to diagnose

  1. Message — Does it say "most likely due to a circular import"?
  2. Version — Installed package version vs the docs/tutorial you follow
  3. Shadowing — Is a local file named like the package?
  4. Structure — Do two of your modules import each other at module level?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.