Skip to content

Python coding guidelines

The Bliss Framework's general coding guidelines were written for application services. Most of our Python is something else: command-line tools and scripts that run next to a project — migration orchestrators, extractors, generators, test harnesses. They are often one file, run with the standard library only, and are read far more often than they are changed.

This section captures how the Bliss principles apply there. Read the general coding guidelines and general naming conventions first — everything here builds on them. PEP 8 applies wherever this page says nothing.

Reference implementation: debee/postgresql/debee.py (orchestrator, one file) and debee-database/check.py (test harness).

What's different from a typical Bliss service

Topic C# / Elixir service Python tool / script
Runtime Long-lived process One run per invocation; exit code is the result
Layering Folders and projects Sections of one file, in a fixed order; modules only when the file is split
Models Classes / structs @dataclass, Enum — never dicts with string keys
Identifiers PascalCase methods snake_case functions and variables, PascalCase classes (PEP 8)
Errors Exceptions + middleware Exceptions inside, one place in main() turns them into a message and an exit code
Output Responses, logs stdout = data, stderr = messages — a tool's output is piped and redirected
Dependencies Package manager Standard library only for tools that ship as a file; declare the minimum Python version

What stays the same

  1. Ubiquitous Language — a CLI operation called runTests is run_tests() in Python, Invoke-Tests in PowerShell, runTests in the docs. Don't rename a concept between implementations.
  2. DRY — regexes, file patterns, magic strings and key sets are module-level constants, defined once at the top.
  3. Use only what you need — a 200-line script needs no Manager class. Add a layer when a second caller appears.
  4. Restrain yourself — one way to print a message, one way to run a subprocess, one way to fail.
  5. Side layer purity — constants, models and helpers don't call providers or management code.

Layering inside one file

A single-file tool keeps the three layers as sections, in this order, separated by a comment banner. A reader finds anything by knowing which layer it belongs to.

#!/usr/bin/env python3
"""extract-db-objects — one paragraph: what it does, what it reads, what it writes.

Requires Python 3.8+, standard library only.
"""

import ...

# --- Constants -------------------------------------------------------------
MIGRATION_FILE_PATTERN = re.compile(r'^(\d{3})_.*\.sql$', re.IGNORECASE)
SOURCE_MIGRATION = 'migration'

# --- Models ----------------------------------------------------------------
@dataclass
class ObjectUpdate: ...

# --- Helpers ---------------------------------------------------------------
def normalize_arg_type(arg: str) -> str: ...

# --- Providers -------------------------------------------------------------
def get_migration_files(directory: Path) -> List[Path]: ...       # files
def run_psql(args: List[str]) -> subprocess.CompletedProcess: ... # psql

# --- Management ------------------------------------------------------------
def extract_objects(files: List[Path]) -> Dict[str, DbObject]: ...

# --- I/O -------------------------------------------------------------------
def generate_markdown(objects) -> str: ...
def parse_arguments(argv) -> argparse.Namespace: ...
def main(argv=None) -> int: ...

if __name__ == '__main__':
    sys.exit(main())
Section Layer Holds Must not
Constants Side compiled regexes, key sets, defaults, closed value lists compute anything at import time beyond literals
Models Side @dataclass records, Enums read files, print
Helpers Side pure functions: parsing a string, normalizing a name, formatting a value touch files, processes, the network or print
Providers Providers one outside resource each: files, a subprocess (psql), an HTTP API call another provider, decide the workflow
Management Management the workflow: which provider, in which order, combining results parse arguments, format output
I/O I/O argument parsing, output formatting (JSON, CSV, Markdown, HTML), main(), exit code contain business rules

A class is fine when the state is real — DebeeOrchestrator holds the resolved configuration that every operation reads. It is still layered: its private methods for psql calls are providers, the public operation methods are management, main() stays outside the class.

When to split into modules: when one file stops being navigable (roughly 1500+ lines, or a second tool needs the same helpers). Then each section becomes a module with the same name: constants.py, models.py, *_helpers.py, *_provider.py, *_manager.py, cli.py. A tool that is distributed as a single file (debee) stays one file and keeps the sections.

Models, not dicts

# BAD — the shape lives in string keys spread through the file
obj = {'schema': schema, 'object_name': name, 'last_update_file': ''}
obj['last_update_fiel'] = file          # typo = silent new key

# GOOD
@dataclass
class DbObject:
    schema: str
    object_name: str
    object_type: ObjectType
    updates: List[ObjectUpdate] = field(default_factory=list)
  • Closed sets of values are an Enum (or a str-valued Enum when they are written to output): ObjectType.FUNCTION, Operation.CREATE_OR_REPLACE.
  • Tuples are for two or three values that are obviously positional ((start, end)); anything with named parts is a dataclass.
  • Convert to dicts only at the I/O edge (dataclasses.asdict for JSON).

Errors and exit codes

  • Inside the tool, raise; don't print and return None, don't sys.exit() from a provider.
  • main() is the one place that catches, prints the message to stderr and returns the exit code: 0 success, 1 failure, 2 usage error (what argparse already uses).
  • Subprocess failures are checked: look at returncode (or use check=True) — a command that failed must not look like it succeeded.

Output streams

  • stdout carries the result — the JSON, the CSV, the report. Someone will run tool > out.json.
  • stderr carries everything else — progress, warnings, summaries: print(..., file=sys.stderr) or the tool's print_info / print_warning helpers built on it.
  • Writing a file is a provider call (save_text(path, text)); the I/O layer decides whether the result goes to a file or stdout.

Subprocesses and files

  • subprocess.run([...]) with a list of arguments, never a shell string. Each argument is one token: '-Fc', or '-F', 'c' — never '-F c' (pg_restore receives " c"; this was debee 1.0.5's restore bug).
  • pathlib.Path for paths; open(..., encoding='utf-8') always explicit; newline='' for CSV.
  • Temp files in tempfile.gettempdir() (or TemporaryDirectory), never next to the user's files, removed in finally.

Type hints and version

  • Every function outside a two-line helper has type hints on parameters and return value.
  • The module docstring states the minimum Python version and checks it against the features used (dataclasses = 3.7, := = 3.8, list[str] in annotations = 3.9, X | None = 3.10). Prefer typing.List / Optional while the minimum is below 3.9.

What this section covers

  • Naming conventions — casing, file names, the verb registry in Python, CLI-operation names, predicates, private names, constants, anti-patterns.

See also