python
naming
ai_generated
true
SyntaxError or ModuleNotFoundError — cannot import module with hyphen in name
ID: python/import-hyphenated-module-name
95%Fix Rate
95%Confidence
4Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Python import system treats hyphens as minus operators: 'import my-module' is parsed as 'import my - module'.
genericWorkarounds
-
98% success Rename the package directory: replace hyphens with underscores
mv my-module my_module # Python convention: underscores for packages, hyphens only in PyPI dist names
Sources: https://peps.python.org/pep-0008/#package-and-module-names
-
75% success If third-party package, use importlib.import_module() as last resort
import importlib; my_module = importlib.import_module('my-module')Sources: https://docs.python.org/3/library/importlib.html#importlib.import_module
Dead Ends
Common approaches that don't work:
-
Use __import__('my-module') for hyphenated names
60% fail
Works but produces unidiomatic code; breaks IDE autocompletion and type checking
-
Add the module to sys.path with importlib
55% fail
importlib.import_module('my-module') works but creates maintenance burden and hides dependencies