Python Modules and Imports

Package layout, absolute imports, and the main guard.

  • python import
  • __main__
  • python -m
  • package layout
  • circular import

Python Modules and Imports

Package layout, absolute imports, and the main guard.

Commands

CommandWhat it does
from pkg.mod import thingAbsolute import (preferred)
dunder-main guardScript entry guard
python -m pkg.modRun a module as a script
init-py markerMarks a directory as a package
sys.path via PYTHONPATHWhere imports are resolved

Example

myapp: init, core, cli modules

FAQ

Relative or absolute imports?

Absolute (from pkg.mod import x) — explicit, refactor-safe, and required by most linters.

Circular import error — fix?

Move shared code to a third module or import inside the function; restructure if it recurs.

常見問題

Relative or absolute imports?
Absolute (from pkg.mod import x) — explicit, refactor-safe, and required by most linters.
Circular import error — fix?
Move shared code to a third module or import inside the function; restructure if it recurs.

Python