LESSON p.2 · Engineering · 150 min

Python engineering habits: environments, files, exceptions, and pytest

Python engineering habits: environments, files, exceptions, and pytest. Learn virtual environments, modules, file I/O, exceptions, assertions, unit tests, and debugging and complet

Learning objectives

  1. Create an isolated environment and record interpreter and dependency versions.
  2. Separate importable logic, command entry points, and tests.
  3. Define failures for file encoding, paths, and invalid input.
  4. Protect refactors with arrange–act–assert pytest tests.

Core concepts

Environment and dependencies

Isolate the project and record the interpreter and key package versions. Rebuilding it in a fresh directory is stronger evidence than “it runs on my laptop”.

Modules and entry points

Put computation in importable functions and keep argument parsing at the boundary. The same logic can then be tested and reused from notebooks or training scripts.

Path and UTF-8

Use pathlib, explicit UTF-8, and temporary directories. String concatenation and the current working directory are hidden dependencies.

Exceptions and assertions

Use exceptions for invalid external inputs and assertions for internal invariants. Catch narrowly and retain context; never silently convert every failure into an empty result.

pytest regression

Fix inputs, execute one behavior, and assert an explicit result. Tests are a safety net for refactoring and vectorization, not a count competition.

Build and verify

Turn a one-off text script into a reproducible project

  • Create src, tests, README, and dependency metadata; record Python version.
  • Split file loading, tokenization, counting, and output.
  • Use tmp_path to test UTF-8, empty files, wrong suffixes, and missing paths.
  • Rebuild from the README and run pytest.

Open the complete interactive lesson