Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tomgrin10/swap-exceptions
Python utility decorator and context manager for swapping exceptions
https://github.com/tomgrin10/swap-exceptions
Last synced: about 5 hours ago
JSON representation
Python utility decorator and context manager for swapping exceptions
- Host: GitHub
- URL: https://github.com/tomgrin10/swap-exceptions
- Owner: tomgrin10
- License: mit
- Created: 2020-08-21T16:59:45.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2020-08-28T14:40:46.000Z (about 4 years ago)
- Last Synced: 2024-10-14T01:18:25.108Z (about 1 month ago)
- Language: Python
- Homepage:
- Size: 40 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# swap-exceptions
[![PyPI](https://img.shields.io/pypi/v/swap-exceptions)](https://pypi.org/project/swap-exceptions/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/swap-exceptions)](https://pypi.org/project/swap-exceptions/)
[![PyPI License](https://img.shields.io/pypi/l/swap-exceptions)](https://pypi.org/project/swap-exceptions/)
[![Code Style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black/)Python utility decorator and context manager for swapping exceptions.
### Basic Usage
As a decorator:
```python
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:
```python
from swap_exceptions import swap_exceptionsdef 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:
```python
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] + 10get_value('c') # ValueError: Incorrect value
```Mapping value can also be a factory that generates the exception:
```python
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
```