Python - Architecture & Best Practices
Overview
Estimated time: 45–60 minutes
Structure maintainable Python apps: clean code guidelines, layered architecture, configuration management, logging, and CLI interfaces.
Learning Objectives
- Organize code into modules/packages with clear boundaries.
- Manage configuration via environment variables and files.
- Set up consistent logging and simple, testable CLI interfaces.
Prerequisites
Structure
myapp/
pyproject.toml
src/
myapp/
__init__.py
config.py
cli.py
core/
__init__.py
logic.py
Configuration
import os
def read_config():
debug = os.getenv("MYAPP_DEBUG", "0") == "1"
return {"debug": debug}
Logging
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logging.info("App started")
CLI (argparse)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args(["Alice"]) # example
print(f"Hello, {args.name}")
Common Pitfalls
- Mixing concerns: business logic entangled with I/O or CLI code.
- Hard-coding configuration; prefer environment variables or config files.
Checks for Understanding
- Why separate the CLI layer from core logic?
- Where should configuration be validated?
Show answers
- To test core logic independently and swap interfaces easily.
- Near the boundary where it’s loaded; keep core logic clean.
Exercises
- Refactor a small script into a package with core/logic.py and cli.py.
- Add logging and a debug flag from environment variables.