python naming ai_generated true

SyntaxError or ModuleNotFoundError — cannot import module with hyphen in name

ID: python/import-hyphenated-module-name

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
4Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Python import system treats hyphens as minus operators: 'import my-module' is parsed as 'import my - module'.

generic

Workarounds

  1. 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

  2. 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:

  1. Use __import__('my-module') for hyphenated names 60% fail

    Works but produces unidiomatic code; breaks IDE autocompletion and type checking

  2. Add the module to sys.path with importlib 55% fail

    importlib.import_module('my-module') works but creates maintenance burden and hides dependencies