Skip to content

Python utility decorator and context manager for swapping exceptions

License

Notifications You must be signed in to change notification settings

tomgrin10/swap-exceptions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Python utility decorator and context manager for swapping exceptions

Resources

License

Stars

Watchers

Forks

Languages