Python 101 · Exceptions, Logging, Unittest

Feb 27, 2016 | Tech Software

Index
Index

Concepts

  • EAFP

    - Easier to Ask for Forgiveness than Permission: A coding style that assumes valid inputs and successful operations, handling potential errors through try...except blocks only after they occur.
  • LBYL

    - Look Before You Leap: A coding style that explicitly checks for all necessary preconditions (using if statements) to ensure an operation will succeed before attempting to execute it.
Python is fundamentally designed for EAFP because it prioritizes readability and performance in the 'happy path,' while avoiding the race conditions and redundant checks common in LBYL.

Exceptions

  • try..except..as..else..finally

    : The standard syntax for handling exceptions.
  • Triggering

    : Manually raise SomeException when the code is technically valid but violates business logic.
  • Re-Raising

    : Re-raise an exception after performing some work (like logging) to allow the caller to handle the original error.
  • Exception Chaining

    : Use raise...from to throw a more relevant exception while preserving the original error's traceback for debugging.
  • Custom Exceptions

    : Define your own 'exception hierarchy' by inheriting from the Exception class to provide more precise error reporting.
Always prefer the with statement for resource management; it is safer, more concise, and eliminates the risk of forgetting to release resources; i.e., use with to handle the finally part and wrap it in a try...except block to handle logic errors.

Logging

  • Design Consideration

    : Core components to be considered in logging; the loguru library has them all.
Dimension Key Concepts Problem Solved
Content Timestamp, File, Func, Line, Col, Msg Tracing: Pinpoint exactly when and where.
Metadata Levels, Stacktrace Filtering: Gauge severity and capture evidence.
Storage Rotation & Retention Survival: Prevent disk overflow and manage history.
Distribution Multi-Handler, Console/File/Cloud Delivery: Debug live vs. persistent storage.
Architecture Global Singleton, Entry Config Consistency: Unified logging across all modules.
Compatibility Structured Logging (e.g. JSON) Searchability: Integration with Cloud tools.
Performance Asynchronous Writing Efficiency: Zero impact on application speed.
Security Data Masking/Anonymization Compliance: Protect sensitive user info.
Tracing Context Binding, Request ID Correlation: Link logs for a single request.
  • Practical Example

    : Showing some of the core design considerations in practice, with loguru.

Unittest

  • Concepts

    : A structured methodology to verify that individual components of software work as intended through isolated execution and validation.
Concept Description
Case The smallest, atomic unit of testing that verifies a specific behavior by comparing an actual outcome against an expected result.
Fixture A baseline set of preconditions (files, database connections, or state) and post-test cleanup to ensure test isolation.
Suite A logical grouping of test cases used to manage execution flow, typically categorized by module, tag, or priority.
Runner The execution engine that automatically discovers test files, manages the lifecycle of fixtures, and provides structured reporting.
  • Frameworks & Example

    : pytest (most popular and preferred), unittest (built-in but not as powerful), and others, see below for a simplistic usage example with pytest.
  • Architecture & Commands

    : Common project structure setup and execution, commonly used in combination with project and dependency managers such as uv (preferred) or poetry.