On this page
  1. Modules, Packages, and Tooling
  2. Contents
  3. Modules, Packages & __all__
  4. The Import System & importlib
  5. Virtual Environments (venv & ensurepip)
  6. Executable Archives (zipapp) & runpy

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__

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

Related notes