brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m package.module runs a file so its package imports work

Python
~/tips/tip-python-m-package-module-imports

python3 mypkg/cli.py # ModuleNotFoundError: No module named 'mypkg'

Run a script inside your package without ModuleNotFoundError on its own imports.

A file inside a package that does from mypkg import helpers often fails with ModuleNotFoundError: No module named 'mypkg' when you run it by path. Running it as a module fixes that.

# project/
#   mypkg/__init__.py
#   mypkg/helpers.py
#   mypkg/cli.py      (from mypkg import helpers)

cd project
python3 mypkg/cli.py     # ModuleNotFoundError: No module named 'mypkg'
python3 -m mypkg.cli     # works

When you run a file by its path, Python puts that file’s own folder, project/mypkg, at the front of the import path. From there, there’s no mypkg to find. With -m, Python puts the current folder on the path instead and imports mypkg.cli as part of its package, so absolute imports and relative ones like from . import helpers both work.

A common fix is sys.path.append(...) at the top of the file or by exporting PYTHONPATH. Both work until someone runs it from a different folder. I’d say -m from the project root is the fix that doesn’t need any of that.

Use dots, not slashes, and leave off .py. You have to be in the folder that contains the package, or have the package installed. If you want python3 -m mypkg on its own to do something, add a __main__.py to the package.

Further reading: python -m, __main__

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link