API Reference

Complete reference documentation for every public symbol in errortools. The pages below are generated from the docstrings in the source tree using sphinx.ext.autodoc; if you spot anything missing or inaccurate, please open an issue on GitHub.

Package layout

errortools is shipped as a single errortools package that re-exports the contents of its submodules. The reference below follows the same layout — every page corresponds to one subpackage or module.

Conventions

Every documented object follows the same conventions as the standard library and the pytest API reference:

  • Type hints use modern PEP 585 syntax (list[int], type[Exception]) where possible.

  • Docstrings follow the Google style; sections like Args, Returns, Raises, and Example are rendered as a structured parameter list.

  • Cross-references use Sphinx roles — {func}`~errortoolsignore```, PureBaseException``, etc. They resolve to the corresponding entry on this page.

Future module

errortools.future

Zero-overhead exception handling for hot paths.

Future-focused lightweight exception handling utilities.

Logging

errortools.logging

A Loguru-inspired structured logger with no external dependencies.

Logging for errortools — loguru-inspired structured logger.

Quick start:

from errortools.logging import logger

logger.info("Hello, {}!", "world")
logger.warning("Disk at {pct}%", pct=90)

# Add a file sink
logger.add("app.log", rotation=10_000_000, retention=5)

# Bind context
req_log = logger.bind(request_id="abc-123")
req_log.debug("Request received")

# Catch exceptions
with logger.catch():
    int("oops")
class errortools.logging.BaseLogger(name='errortools', extra=None)[source]

Bases: object

A loguru-inspired logger with structured sinks, level filtering, and context binding.

Key features

  • Leveled methods: trace, debug, info, success, warning, error, critical

  • Sink management: add/remove multiple typed sinks via add / remove (stream, file, or any callable)

  • Context binding: create child loggers with extra fields via bind — original logger is untouched

  • Exception capture: pass exception=True (or use exception) to attach the current traceback to any record

  • Level control: change the minimum level at runtime via set_level

Usage:

from errortools.logging import logger

logger.info("Server started on port {}", 8080)
logger.warning("Disk usage at {pct:.1f}%", pct=92.5)

with logger.catch():
    risky_operation()

db_log = logger.bind(db="postgres", user="admin")
db_log.debug("Query executed in {ms}ms", ms=42)
add(sink, *, level=Level.DEBUG, colorize=None, rotation=0, retention=0, encoding='utf-8', fmt=None)[source]

Register a new sink and return its integer handle.

Parameters:
  • sink (IO[str] | str | Callable[[str], None] | BaseSink) –

    Destination — one of:

    • A writable text stream (sys.stderr, sys.stdout, …)

    • A file path string or pathlib.Path

    • A callable (message: str) -> None

    • A sink.BaseSink instance

  • level (str | int | Level) – Minimum log level for this sink. Accepts a level.Level, a level name string, or a numeric value.

  • colorize (bool | None) – Force colour on/off for stream sinks. None auto-detects TTY.

  • rotation (int) – Byte threshold for file rotation (file sinks only).

  • retention (int) – Number of rotated files to keep (file sinks only).

  • encoding (str) – File encoding (file sinks only).

  • fmt (str | None) – Custom format string.

Returns:

An integer sink ID that can be passed to remove.

Return type:

int

remove(sink_id=None)[source]

Remove a sink by its ID, or remove all sinks if sink_id is None.

Parameters:

sink_id (int | None) – Handle returned by add. Pass None to clear all.

Return type:

None

set_level(level)[source]

Set the global minimum level for this logger.

Individual sinks can still have their own, stricter filters.

Parameters:

level (str | int | Level) – Level name, numeric value, or level.Level.

Return type:

None

property level: Level

The current global minimum level.Level.

bind(**kwargs)[source]

Return a new logger that carries extra context fields.

The original logger is unmodified. Bound fields appear in record.extra and can be accessed in custom format strings.

Example:

req_log = logger.bind(request_id="abc-123")
req_log.info("Received request")  # record.extra["request_id"] == "abc-123"
Parameters:

kwargs (Any)

Return type:

BaseLogger

log(level, message, *args, exception=False, depth=1, **kwargs)[source]

Emit a log record at an arbitrary level.

Parameters:
  • level (str | int | Level) – Level name, numeric value, or level.Level.

  • message (str) – Message template. Supports str.format-style positional ({}) and keyword ({key}) placeholders.

  • *args (Any) – Positional arguments for the message template.

  • exception (bool) – Capture the current exception info (like loguru’s opt(exception=True)).

  • depth (int) – Stack depth offset for caller location detection.

  • **kwargs (Any) – Keyword arguments for the message template.

Return type:

None

trace(message, *args, **kwargs)[source]

Log at TRACE level (numeric 5).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

debug(message, *args, **kwargs)[source]

Log at DEBUG level (numeric 10).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

info(message, *args, **kwargs)[source]

Log at INFO level (numeric 20).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

success(message, *args, **kwargs)[source]

Log at SUCCESS level (numeric 25).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

warning(message, *args, **kwargs)[source]

Log at WARNING level (numeric 30).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

error(message, *args, **kwargs)[source]

Log at ERROR level (numeric 40).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

critical(message, *args, **kwargs)[source]

Log at CRITICAL level (numeric 50).

Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

exception(message, *args, **kwargs)[source]

Log at ERROR level and attach the current exception traceback.

Equivalent to logger.error(message, exception=True).

Example:

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Math went wrong")
Parameters:
  • message (str)

  • args (Any)

  • kwargs (Any)

Return type:

None

catch(*exceptions, level=Level.ERROR, reraise=False, message="An error has been caught in function '{}', process '{}', thread '{}'")[source]

Context manager / decorator that logs uncaught exceptions.

Similar to loguru’s logger.catch().

Parameters:
  • *exceptions (type[BaseException]) – Exception types to catch. Defaults to Exception.

  • level (str | int | Level) – Log level to use when logging the exception.

  • reraise (bool) – If True, re-raise after logging.

  • message (str) – Message template — receives (function, process_id, thread_name).

Return type:

_CatchContext

Example:

with logger.catch():
    int("not a number")

@logger.catch(reraise=True)
def risky():
    ...
opt(*, exception=False, depth=0, lazy=False)[source]

Return a temporary wrapper with extra options.

Parameters:
  • exception (bool) – Capture current exception info for the next log call.

  • depth (int) – Additional stack depth offset for caller location.

  • lazy (bool) – Ignored (reserved for future lazy-evaluation support).

Return type:

_OptLogger

Example:

logger.opt(exception=True).error("Something went wrong")
Parameters:
  • name (str)

  • extra (Union[dict[str, Any], None])

class errortools.logging.Level(name, no, color, icon)[source]

Bases: object

Represents a single log level with a name, numeric value, and ANSI color.

Parameters:
  • name (str)

  • no (int)

  • color (str)

  • icon (str)

name: str
no: int
color: str
icon: str
TRACE: ClassVar[Level] = Level(name='TRACE', no=5, color='\x1b[34m', icon='✎')
DEBUG: ClassVar[Level] = Level(name='DEBUG', no=10, color='\x1b[36m', icon='⚙')
INFO: ClassVar[Level] = Level(name='INFO', no=20, color='\x1b[32m', icon='ℹ')
SUCCESS: ClassVar[Level] = Level(name='SUCCESS', no=25, color='\x1b[92m', icon='✔')
WARNING: ClassVar[Level] = Level(name='WARNING', no=30, color='\x1b[33m', icon='⚠')
ERROR: ClassVar[Level] = Level(name='ERROR', no=40, color='\x1b[31m', icon='✘')
CRITICAL: ClassVar[Level] = Level(name='CRITICAL', no=50, color='\x1b[1;31m', icon='☠')
errortools.logging.get_level(name_or_no)[source]

Return a Level by name (case-insensitive) or numeric value.

Raises:

KeyError – If the level is not found.

Parameters:

name_or_no (str | int)

Return type:

Level

class errortools.logging.Record(time, level, message, name, file, line, function, thread_id, thread_name, process_id, exception, extra=<factory>)[source]

Bases: object

Immutable snapshot of a single log event.

Mirrors loguru’s record dict but as a typed dataclass.

Variables:
  • time (datetime.datetime) – UTC timestamp when the record was created.

  • level (_errortools.logging.level.Level) – The logging.level.Level of this event.

  • message (str) – The formatted log message (after str.format / f-string).

  • name (str) – Logger name (set by the caller or auto-detected).

  • file (str) – Source file name (__file__).

  • line (int) – Source line number.

  • function (str) – Calling function name.

  • thread_id (int) – OS thread identifier.

  • thread_name (str) – Thread name.

  • process_id (int) – OS process id.

  • exception (tuple[type[BaseException], BaseException, types.TracebackType | None] | None) – The active exception info tuple, or None.

  • extra (dict[str, Any]) – Arbitrary key/value context bound via logger.bind().

Parameters:
  • time (datetime)

  • level (Level)

  • message (str)

  • name (str)

  • file (str)

  • line (int)

  • function (str)

  • thread_id (int)

  • thread_name (str)

  • process_id (int)

  • exception (tuple[type[BaseException], BaseException, TracebackType | None] | None)

  • extra (dict[str, Any])

time: datetime
level: Level
message: str
name: str
file: str
line: int
function: str
thread_id: int
thread_name: str
process_id: int
exception: tuple[type[BaseException], BaseException, TracebackType | None] | None
extra: dict[str, Any]
property exc_text: str | None

Formatted traceback string, or None if no exception.

class errortools.logging.BaseSink[source]

Bases: ABC

Abstract base class for log sinks.

abstractmethod emit(record)[source]

Write record to this sink.

Parameters:

record (Record)

Return type:

None

close()[source]

Optional cleanup called when sink is removed.

Return type:

None

class errortools.logging.StreamSink(stream=None, level=Level.DEBUG, colorize=None, fmt=None)[source]

Bases: BaseSink

Write colourised log lines to a text stream (default: sys.stderr).

Parameters:
  • stream (Union[IO[str], None]) – Writable text stream. Defaults to sys.stderr.

  • level (Level) – Minimum level to emit. Defaults to Level.DEBUG.

  • colorize (Union[bool, None]) – Force colour on/off. None (default) auto-detects TTY.

  • fmt (Union[str, None]) – Custom format string. None uses the default format.

  • diagnose – Include exception variable values in tracebacks (future).

emit(record)[source]

Write record to this sink.

Parameters:

record (Record)

Return type:

None

class errortools.logging.FileSink(path, level=Level.DEBUG, rotation=0, retention=0, encoding='utf-8', fmt=None)[source]

Bases: BaseSink

Write plain-text log lines to a file, with optional size-based rotation.

Parameters:
  • path (Union[str, Path]) – Path to the log file. Parent directories are created.

  • level (Level) – Minimum level to emit. Defaults to Level.DEBUG.

  • rotation (int) – Maximum file size in bytes before rotation. 0 = no rotation.

  • retention (int) – Number of rotated files to keep (oldest are deleted). 0 = keep all.

  • encoding (str) – File encoding. Defaults to "utf-8".

  • fmt (Union[str, None]) – Custom format string. None uses the default format.

emit(record)[source]

Write record to this sink.

Parameters:

record (Record)

Return type:

None

close()[source]

Optional cleanup called when sink is removed.

Return type:

None

class errortools.logging.CallableSink(func, level=Level.DEBUG)[source]

Bases: BaseSink

Wrap a plain callable as a sink.

The callable receives a fully-rendered str (the formatted log line).

Parameters:
  • func (Any) – (message: str) -> None callable.

  • level (Level) – Minimum level to emit.

emit(record)[source]

Write record to this sink.

Parameters:

record (Record)

Return type:

None

Type aliases

errortools.ExceptionType

type(object) -> the object’s type type(name, bases, dict, **kwds) -> a new type

alias of type[Exception]

errortools.WarningType

type(object) -> the object’s type type(name, bases, dict, **kwds) -> a new type

alias of type[Warning]

errortools.AnyErrorCode

alias of InvalidInputError | AccessDeniedError | NotFoundError | RuntimeFailure | TimeoutFailure | ConfigurationError

Version utilities

Lightweight helpers for representing, parsing, and comparing the package’s own (major, minor, patch) version triple programmatically.

  • VersionInfo — a hashable, totally-ordered dataclass for an individual version triple.

  • get_version_tuple() — parse a dotted-decimal version string into a (major, minor, patch) tuple.