The essentials

Quick reference

One focused task per row. Jump to the related section for complete, working examples.

UseSyntaxExamples
Import a moduleimport statisticsView examples
Import a namefrom pathlib import PathView examples
Alias an importimport collections.abc as cabcView examples
Guard script entryif __name__ == '__main__': main()View examples
Run by module namepython -m package.moduleView examples
Regular package markerpackage/__init__.pyView examples
Relative importfrom .formatting import renderView examples
Declare star-import names__all__ = ['Client', 'connect']View examples
Inspect module identityprint(module.__name__)View examples
Inspect source locationprint(module.__file__)View examples
Find without importingspec = importlib.util.find_spec('package.module')View examples
Read package datatext = resources.files('package').joinpath('defaults.json').read_text()View examples

A module is an importable namespace, commonly backed by one Python file; a package organizes modules under a dotted name. Keep imports explicit, avoid executing expensive or stateful work at import time, and run package entry points with -m so Python establishes the intended import context.

Step by step

Detailed examples

01

Prefer explicit namespaces

import module keeps origins visible at use sites; from-import is useful for a few stable names. Imports execute a module's top-level code once per interpreter cache entry. Avoid wildcard imports because they hide provenance and make API changes unpredictable.

Use module and direct-name forms
import statistics
from pathlib import Path

values = [2, 4, 6]
print(statistics.mean(values))
print(Path('report.txt').suffix)
Output
4
.txt
Back to quick reference ↑
02

Separate reusable definitions from entry behavior

When imported, __name__ is the module's qualified name; when run as the main module, it is __main__. Put CLI behavior in main and protect the call. `python -m` searches the import path and supports relative imports inside a package better than executing an internal file path directly.

Testable entry point
def main(argv=None):
    args = ['status'] if argv is None else argv
    print(','.join(args))
    return 0

if __name__ == '__main__':
    raise SystemExit(main())
Output
status
Back to quick reference ↑
03

Keep package direction clear

Regular packages contain __init__.py; namespace packages may span directories without it. Absolute imports are clearest across top-level packages, while explicit relative imports express internal sibling relationships. Avoid circular imports by moving shared contracts downward or importing within a narrow function only when justified.

Small regular package layout
reporting/
├── __init__.py
├── __main__.py
├── formatting.py
└── cli.py

Note: Inside cli.py, `from .formatting import render` imports the sibling module.

Back to quick reference ↑
04

Expose a deliberate package surface

__init__.py can re-export stable public names so callers do not depend on internal layout. __all__ controls star imports but does not make other attributes private. Prefix implementation details with an underscore and document compatibility instead of relying on access enforcement.

Package facade
class Client:
    pass

def connect():
    return Client()

__all__ = ['Client', 'connect']
print([name for name in __all__])
Output
['Client', 'connect']
Back to quick reference ↑
05

Diagnose import resolution before editing sys.path

Python searches built-ins, configured finders, and entries in sys.path. The first matching name wins, so local files can shadow standard or third-party modules. Inspect __spec__, __file__, and find_spec; do not patch sys.path in library code to conceal an incorrect package layout.

Locate a standard module
import importlib.util
import json

spec = importlib.util.find_spec('json')
print(json.__name__)
print(spec.name)
print(spec.origin.endswith('__init__.py'))
Output
json
json
True
Back to quick reference ↑
06

Access data through the package loader

Package data may live in a wheel or other loader context and need not be beside the current working directory. importlib.resources provides traversable resources and temporary filesystem access when an external API requires a path. Declare resource files in packaging configuration.

Read a standard package resource API safely
from importlib import resources

root = resources.files('importlib')
print(root.name)
print(root.is_dir())
Output
importlib
True
Back to quick reference ↑

Local code tester

Inspect module metadata

Import standard modules and inspect names, specs, origins, and public APIs.

Runs in your browser
Output
Press Run to load Python locally.

Sources and further reading

References

Authoritative documentation used to verify and expand this cheat sheet.

  1. Python Software FoundationPython Tutorial: Modulesdocs.python.org
  2. Python Software FoundationThe import systemdocs.python.org
  3. Python Software Foundationimportlib.resourcesdocs.python.org

Help us improve

Found a typo or missing example?

Tell us what would make this cheat sheet clearer, more complete, or more useful.

Share feedback