The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Import a module | import statistics | View examples |
| Import a name | from pathlib import Path | View examples |
| Alias an import | import collections.abc as cabc | View examples |
| Guard script entry | if __name__ == '__main__': main() | View examples |
| Run by module name | python -m package.module | View examples |
| Regular package marker | package/__init__.py | View examples |
| Relative import | from .formatting import render | View examples |
| Declare star-import names | __all__ = ['Client', 'connect'] | View examples |
| Inspect module identity | print(module.__name__) | View examples |
| Inspect source location | print(module.__file__) | View examples |
| Find without importing | spec = importlib.util.find_spec('package.module') | View examples |
| Read package data | text = 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
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.
import statistics
from pathlib import Path
values = [2, 4, 6]
print(statistics.mean(values))
print(Path('report.txt').suffix) 4
.txtSeparate 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.
def main(argv=None):
args = ['status'] if argv is None else argv
print(','.join(args))
return 0
if __name__ == '__main__':
raise SystemExit(main()) statusKeep 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.
reporting/
├── __init__.py
├── __main__.py
├── formatting.py
└── cli.py Note: Inside cli.py, `from .formatting import render` imports the sibling module.
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.
class Client:
pass
def connect():
return Client()
__all__ = ['Client', 'connect']
print([name for name in __all__]) ['Client', 'connect']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.
import importlib.util
import json
spec = importlib.util.find_spec('json')
print(json.__name__)
print(spec.name)
print(spec.origin.endswith('__init__.py')) json
json
TrueAccess 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.
from importlib import resources
root = resources.files('importlib')
print(root.name)
print(root.is_dir()) importlib
TrueLocal code tester
Inspect module metadata
Import standard modules and inspect names, specs, origins, and public APIs.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



