On this page
Modules, Packages, and Tooling
Prev: Error Handling and Context Managers | Up: Intermediate Python & Software Engineering | Next: Type Hinting and Static Analysis
Rel: importlib, venv, ensurepip, zipapp, runpy, sys, sysconfig
Ref: docs.python.org — Modules | docs.python.org — venv
Tags: #public #python3 #tutorials #software-engineering #modules #packaging
Contents
- > Modules, Packages & `__all__`
- > The Import System & `importlib`
- > Virtual Environments (`venv` & `ensurepip`)
- > Executable Archives (`zipapp`) & `runpy`
Modules, Packages & __all__
- A module is a single
.pyfile. - A package is a directory containing submodules and typically an
__init__.py(or a PEP 420 namespace package without__init__.py). - Define
__all__ = ["public_fn", "PublicClass"]to control whatfrom pkg import *exports and document the public API. - Guard executable entry points with
if __name__ == "__main__":so importing the module does not trigger side effects.
my_app/
├── __init__.py # Package initialization & re-exports
├── __main__.py # Entry point for `python3 -m my_app`
├── core.py
└── utils/
├── __init__.py
└── formatting.py
The Import System & importlib
Python resolves imports by checking sys.modules (cache), then searching sys.meta_path finders and sys.path directories. Use [[stdlib_module/importlib|importlib]] for dynamic imports and package metadata/resource loading.
import importlib
import importlib.metadata
import sys
# Dynamic import by module name
math_mod = importlib.import_module("math")
print(math_mod.factorial(5)) # 120
# Inspect module search path and loaded cache
print("stdlib loaded:", "json" in sys.modules)
print("sys.path entries:", len(sys.path))
Virtual Environments (venv & ensurepip)
[[stdlib_module/venv|venv]] creates isolated Python environments using only the standard library, separating per-project dependencies from the system interpreter.
# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate # macOS / Linux
# .venv\Scripts\activate # Windows
You can also create and inspect environments programmatically with venv and [[stdlib_module/sys|sys]]:
import sys
import venv
from pathlib import Path
import tempfile
def in_virtualenv() -> bool:
return sys.prefix != sys.base_prefix
with tempfile.TemporaryDirectory() as tmp:
env_dir = Path(tmp) / "demo_venv"
venv.create(env_dir, with_pip=False)
print("Created venv at:", env_dir, "exists:", (env_dir / "pyvenv.cfg").exists())
Executable Archives (zipapp) & runpy
[[stdlib_module/zipapp|zipapp]] bundles a pure-Python package directory into a single executable .pyz archive, and [[stdlib_module/runpy|runpy]] executes modules by dotted name (powering python3 -m).
import tempfile
import zipapp
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "hello_app"
src.mkdir()
(src / "__main__.py").write_text('print("Hello from zipapp!")\n', encoding="utf-8")
archive = Path(tmp) / "hello.pyz"
zipapp.create_archive(src, target=archive)
print("Archive built:", archive.name, archive.stat().st_size, "bytes")
Linked from
- tuts/python3/tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modules_packages_and_tooling
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis
- tuts/third_party/python3/maturin
Related notes
- tuts/python3/tutorials/intermediate_python_and_software_engineering Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/type_hinting_and_static_analysis Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/third_party/python3/maturin links to this page; shared tags: #packaging
- tuts/python3/stdlib_module/ensurepip Linked here
- tuts/python3/stdlib_module/importlib Linked here
- tuts/python3/stdlib_module/runpy Linked here
- tuts/python3/stdlib_module/sys Linked here
- tuts/python3/stdlib_module/sysconfig Linked here