https://github.com/tomgrin10/swap-exceptions
Python utility decorator and context manager for swapping exceptions
https://github.com/tomgrin10/swap-exceptions
Last synced: 10 days 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 (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2020-08-28T14:40:46.000Z (almost 5 years ago)
- Last Synced: 2025-05-17T09:09:17.133Z (about 2 months ago)
- Language: Python
- Homepage:
- Size: 40 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# swap-exceptions
[](https://pypi.org/project/swap-exceptions/)
[](https://pypi.org/project/swap-exceptions/)
[](https://pypi.org/project/swap-exceptions/)
[](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
```