Skip to main content

Python utility decorator and context manager for swapping exceptions

Project description

swap-exceptions

PyPI PyPI - Python Version PyPI License Code Style: black

Python utility decorator and context manager for swapping exceptions.

Basic Usage

As a decorator:

from swap_exceptions import swap_exceptions

@swap_exceptions({KeyError: ValueError("Incorrect value")})
def get_value(key: str):
    d = {'a': 1, 'b': 2}
    return d[key]

get_value('c')  # ValueError: Incorrect value

Or as a context manager:

from swap_exceptions import swap_exceptions

def get_value(key: str):
    d = {'a': 1, 'b': 2}
    with swap_exceptions({KeyError: ValueError("Incorrect value")}):
        return d[key]

get_value('c')  # ValueError: Incorrect value

Advanced Usage

Mapping key can also be a tuple:

from swap_exceptions import swap_exceptions

@swap_exceptions({(KeyError, TypeError): ValueError("Incorrect value")})
def get_value(key: str):
    d = {'a': 1, 'b': 2, 'c': 'not a number'}
    return d[key] + 10

get_value('c')  # ValueError: Incorrect value

Mapping value can also be a factory that generates the exception:

from swap_exceptions import swap_exceptions

@swap_exceptions({KeyError: lambda e: ValueError(f"Incorrect value {e.args[0]}")})
def get_value(key: str):
    d = {'a': 1, 'b': 2}
    return d[key]

get_value('c')  # ValueError: Incorrect value c

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for swap-exceptions, version 1.0.2
Filename, size File type Python version Upload date Hashes
Filename, size swap_exceptions-1.0.2-py2.py3-none-any.whl (3.4 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size swap-exceptions-1.0.2.tar.gz (3.5 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page