Skip to main content

safecatch

Safecatch is a lightweight Python package that provides decorators for streamlined exception handling.

It helps reduce repetitive try/except boilerplate while keeping application logic focused and readable.

Safecatch is designed for:

  • graceful degradation,
  • expected failure handling,
  • resilience patterns,
  • and cleaner recovery logic.

Installation

pip install safecatch

Usage

Single Exception Handling

Use safecatch_handler to catch a single expected exception and provide a fallback value or fallback function.

from safecatch.safecatch import safecatch_handler

@safecatch_handler(ZeroDivisionError, 0)
def divide(a, b):
    return a / b

print(divide(10, 2))  # 5.0
print(divide(10, 0))  # 0

Using a Fallback Function

Fallback functions allow custom recovery behavior.

from safecatch.safecatch import safecatch_handler

def fallback_division(a, b):
    print("Division by zero occurred")
    return 0

@safecatch_handler(ZeroDivisionError, fallback_division)
def divide(a, b):
    return a / b

print(divide(10, 0))

Multiple Exception Handling

Use multi_safecatch_handler to define different recovery behavior for different exceptions.

from safecatch.multi_safecatch import multi_safecatch_handler

def handle_value_error(x, y):
    print(f"Invalid value detected: x={x}, y={y}")
    return -1

@multi_safecatch_handler({
    ZeroDivisionError: 0,
    ValueError: handle_value_error
})
def test_func(x, y):
    if y == 0:
        return x / y

    if y < 0:
        raise ValueError("Negative value")

    return x + y

print(test_func(3, 2))   # 5
print(test_func(3, 0))   # 0
print(test_func(3, -1))  # -1

Recommended Usage Patterns

Safecatch works best when handling:

  • expected operational failures,
  • recoverable errors,
  • external system instability.

Examples:

  • API request timeouts
  • Missing cache entries
  • Optional file loading
  • Temporary database connectivity issues
  • User-provided input parsing

Example:

from requests.exceptions import Timeout

@safecatch_handler(Timeout, {})
def fetch_user_data():
    return external_api_call()

Anti-Patterns

Avoid broad exception suppression.

Avoid This

@safecatch_handler(Exception, None)
def process_data():
    ...

This can:

  • hide programming bugs,
  • suppress critical failures,
  • make debugging difficult,
  • create silent production issues.

Prefer Specific Exceptions

@safecatch_handler(FileNotFoundError, [])
def load_optional_config():
    ...

Specific exception handling is safer and easier to debug.

Features

  • safecatch_handler

    • Catch a specific exception
    • Return a fallback value
    • Or execute a fallback function
  • multi_safecatch_handler

    • Handle multiple exception types
    • Use different recovery strategies per exception
  • Lightweight and dependency-free

  • Designed for readable recovery logic

Debugging and Observability

Safecatch should be used together with:

  • proper logging,
  • monitoring,
  • exception tracking tools.

Even when exceptions are intentionally handled, failures should remain observable.

Recommended tools:

  • logging
  • Sentry
  • OpenTelemetry
  • metrics dashboards

How It Works

Safecatch abstracts repetitive exception handling into reusable decorators.

Instead of repeatedly writing:

try:
    ...
except SomeError:
    ...

You define reusable recovery behavior once and apply it declaratively.


safecatch_handler

Takes:

  • an exception type,
  • and a fallback value or fallback function.

If the decorated function raises the specified exception:

  • the exception is intercepted,
  • and the fallback behavior is executed.

multi_safecatch_handler

Accepts a dictionary mapping:

  • exception types
  • to fallback values or fallback functions.

If an exception is raised:

  • the matching recovery behavior is executed,
  • otherwise the exception propagates normally.

Testing

Safecatch includes tests written with pytest.

Run tests locally:

pip install -e .
pip install -r tests/requirements.txt
pytest tests/

Philosophy

Safecatch is not intended to silently hide unexpected bugs.

The package is built around one principle:

Catch only expected failures.

Good use cases:

  • network timeouts,
  • missing optional files,
  • API fallbacks,
  • transient failures,
  • non-critical parsing issues.

Bad use cases:

  • catching broad Exception,
  • suppressing programming bugs,
  • hiding production errors,
  • ignoring unexpected behavior.

Safecatch should improve resilience without sacrificing debuggability.

Contributing

Contributions are welcome.

Suggested areas for contribution:

  • logging support,
  • async support,
  • retry strategies,
  • observability integrations,
  • documentation improvements,
  • typing enhancements.

Please open an issue or submit a pull request on the GitHub repository.

Future Direction

Safecatch aims to evolve into a lightweight resilience and recovery utility for Python applications.

Planned areas of improvement include:

  • retry support,
  • async support,
  • telemetry and observability,
  • structured result objects,
  • production-safe exception handling patterns.

Metadata

Release files for safecatch 1.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for safecatch 1.0.5
File Size Uploaded Provenance Actions
safecatch-1.0.5.tar.gz 5.7 kB Without provenance Details for safecatch-1.0.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for safecatch 1.0.5
File Interpreter ABI Platform Actions
safecatch-1.0.5-py3-none-any.whl Python 3 none any Details for safecatch-1.0.5-py3-none-any.whl

Total release size: 10.5 kB

Release files / safecatch-1.0.5.tar.gz

Download URL safecatch-1.0.5.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b06051d66bd8eae101e58c8f2ebe696a6e0adf8a165382b8c61650931b7a2c69
BLAKE2b-256 checksum
How to use checksums
8e9551bef5f7aa7f86bfc46d2a21ccffe8bfd43fca1ec6731f8926cb6876fd29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / safecatch-1.0.5-py3-none-any.whl

Download URL safecatch-1.0.5-py3-none-any.whl
Size 4.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6a4d274d37a16021a2cbce3ecbca469eefc2254427cdb8f39a6ec192d7a566d4
BLAKE2b-256 checksum
How to use checksums
e912f5f7924898d77f3ff73d930ee027730fa059f942a4de99e21920aa702007
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Security for safecatch 1.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page