← Debugging Guides

阅读中文版本

Python AttributeError: module has no attribute

Fix AttributeError when a module attribute is missing because of version drift, a shadowing local file, or a wrong import form.

intermediatedebuggingpythonimportsdependencies

Symptoms

  • AttributeError: module 'X' has no attribute 'Y'
  • A library API worked yesterday and fails after an upgrade
  • The error mentions your own module name unexpectedly

Possible causes

  • The installed library version does not expose that attribute
  • A local file named like the dependency shadows the real package
  • The attribute lives on a submodule you did not import
  • An optional dependency is missing and the attribute is conditionally defined

Diagnosis steps

Inspect what the module actually provides

python -c "import X; print(dir(X))"

Interpretation

The listing shows whether the attribute exists at all in this version.

Print the module file path

python -c "import X; print(X.__file__)"

Interpretation

If the path is in your project directory, a local file is shadowing the package.

Check the installed version

pip show X

Interpretation

Compare with the docs for that exact version; APIs move between releases.

Root cause

Python attribute access fails when the object genuinely lacks the attribute: the installed version may have renamed or removed it, a same-named local module may shadow the dependency, or the attribute may live in a submodule that was never imported. The import succeeds at module level, so the error only appears at attribute access.

Fix

Confirm the installed version and align the call to its documented API, or pin the dependency. Rename any local module that shadows a package and clear stale .pyc caches. Import the correct submodule explicitly, and guard optional features with hasattr or a try/except ImportError.

Verify the fix

Re-run the script; the attribute resolves and the call succeeds. Add a smoke test importing the module and touching the used attribute so version drift is caught in CI.

Symptoms

You see AttributeError: module 'X' has no attribute 'Y'. The import itself is fine, and the failure is specific to one attribute. It often coincides with a dependency upgrade or a new file in the project root.

Diagnosis

List the module’s real attributes and where it loads from:

import numpy as np
print(np.__file__)
print([a for a in dir(np) if 'nd' in a])

If __file__ points inside your project, a local file shadows the package.

Fix

Align with the installed version, and rename shadowing files:

pip show numpy
mv numpy.py legacy_numpy_helper.py
find . -name '*.pyc' -delete

For optional features, use a guarded import instead of assuming the attribute exists.

Verification

Re-run the code and confirm the attribute resolves. A CI smoke test that touches the used attributes catches future version drift before deploy.