error.py


Overview

The [error.py](/projects/286/67543) module provides a structured and extensible mechanism for handling operating system errors (errno) by creating specific exception classes dynamically based on the POSIX `errno` values. This approach allows the program to raise and catch meaningful, errno-specific exceptions rather than generic `OSError` or [EnvironmentError](/projects/286/67579) exceptions.

Key features include:

This module is useful in larger systems dealing with OS-level IO or filesystem operations, making error handling more precise and expressive.


Classes and Functions

Class: Error

A subclass of [EnvironmentError](/projects/286/67579) that represents an OS error corresponding to a specific errno. It provides customized string and representation methods for clearer debugging messages.

Methods:


Class: ErrorMaker

A factory class that lazily creates and caches custom exception classes for each errno defined in the POSIX standard (`errno` module). Each generated class:

This class also provides a utility to call functions and automatically raise the appropriate errno-specific exception on failure.

Attributes:

Methods:


Function: __getattr__(attr: str) -> type[Error]

Module-level magic function to enable lazy retrieval of errno exception classes by attribute name on the module itself.

**Example:**

from error import ENOENT

try:
    raise ENOENT("File does not exist")
except ENOENT as e:
    print(e)

This function internally delegates to the singleton `_error_maker` instance.


Important Implementation Details


Interaction with Other Parts of the System


Usage Example

from error import checked_call, ENOENT

def delete_file(path):
    # This will raise ENOENT if file does not exist
    checked_call(os.remove, path)

try:
    delete_file("missing.txt")
except ENOENT as e:
    print(f"File not found: {e}")

Diagram

classDiagram
    class Error {
        +__repr__() str
        +__str__() str
    }

    class ErrorMaker {
        -_errno2class: dict[int, type[Error]]
        +__getattr__(name: str) type[Error]
        -_geterrnoclass(eno: int) type[Error]
        +checked_call(func: Callable, *args, **kwargs) R
    }

    ErrorMaker --> Error : subclasses

Summary

The [error.py](/projects/286/67543) module provides a dynamic, lazy-loading system for creating and raising errno-specific exceptions, improving error clarity for OS and IO operations. It wraps system calls to raise meaningful exceptions tied directly to the POSIX error codes, facilitating more precise error handling in applications dealing with file and OS level operations.