Exception group utilities for exceptional code
Project description
groupie is a module for useful ExceptionGroups
Exceptions in Python can be a very neat way of controling program flow. ExceptionGroups (with an assist from groupie) simplify more complex control flow.
It's features include:
- Collect exceptions using a context, like
contextlib.suppress- but collect them up accumulateexceptions into one bigExceptionGroupto be raised at oncedowngradeexceptions to warnings presented vialogging- Static analysis (eg.
ruff) compatability notices when you're supressing errors
Think of using this when:
- Parsing configuration files / objects
- Parsing code
- Building a bunch of targets
Useful Patterns
Surface as many user-facing issues as possible at once
It's super annoying as a user to get drip-fed one issue at a time, especially when there's some intensive process leading up to the failure (imagine if pytest stopped at the first failed test each time it was run).
Raise these exceptions for any branch of logic that will individually stop execution, but accumulating these before raising them means that all possible branches are explored as deeply as possible before surfacing the issue.
eg.
time_consuming_setup()
with accumulate(ValueError) as accumulator:
with accumulator.collector:
do_one() # <-- say this fails, we'd usually never know if two and three were going to work!
with accumulator.collector:
do_two()
with accumulator.collector:
do_three() # <-- this fails as well!
This will yield an ExceptionGroup showing both do_one and do_three failed at the same time!
Accumulating exceptions in a loop
Because it's so common, there are special methods to condense the boilerplate of accumulating exceptions in a loop.
for collector, item in accumulate(range(10), ValueError):
with collector:
do_something(item)
Then the exception group will contain all the exceptions raised in the loop.
downgradeing Exceptions
Say you've deprecated something, but you want to surface it as a warning, later to be promoted to an error:
def do_something():
with downgrade(DeprecationException):
raise DeprecationException("This is deprecated - to the other thing.")
# but, for now, do it anyway...
Attempting to do something a few ways, failing only if none succeed
A common pattern for a user-facing application is to attempt to do something - perhaps load a configuration file - a few different ways, and only fail if none succeed.
Say you allow the configuration file for a tool to exist in a few places.
def load_config():
possible_locations = [
"~/.config/my-tool/config.json",
"./config.json",
"/etc/my-tool/config.json",
]
collector = Collector(FileNotFoundError)
for location in possible_locations:
with collector:
return load_config_from_file(location)
# If we haven't already returned, raise an exception describing
# all the failures we encountered while trying.
collector.raise_all()
NOTE: the difference accumulate and Collector:
accumulateis a context manager that accumulates the exceptions into a single one, and then raises it when exiting the context. It's useful to ensure you definately raise the exception and makes it really hard to miss a check on whether there were any.- The
Collectoris a context manager that collects the exceptions, but it's up to you to handle them (possibly raise them) when you're done with it.
Custom UserException tree
One very useful pattern is to create a tree of Exception types under the standard included types and use them to represent user-facing issues.
class UserException(Exception):
"""Represents a user-facing exception"""
class UserResourceException(UserException):
"""You have a file missing!"""
# etc...
This is particulaly useful because you can pass the UserException type to all the accumulate calls around your code.
You can also add pretty printing to these exceptions (check out rich!) with something like:
class UserException(Exception):
"""Represents a user-facing exception"""
def __str__(self):
return f"{self.__class__.__name__}: {self.__doc__}"
Attribution
These utils and patternsstarted life as part of atopile, a compiler to design PCBAs with code
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file groupie-0.1.0.tar.gz.
File metadata
- Download URL: groupie-0.1.0.tar.gz
- Upload date:
- Size: 16.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0cfb2ea35cc447aeb7d2b1f9d8cb46cb3dbdf11014dd32780a2ee0638eda69ab
|
|
| MD5 |
6901282891aff03401af2ed28820b3c0
|
|
| BLAKE2b-256 |
80519081ab242e19c99d2023701a80e4de00a33734397a50fb9d8e967099fbca
|
Provenance
The following attestation bundles were made for groupie-0.1.0.tar.gz:
Publisher:
release.yml on mawildoer/groupie
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
groupie-0.1.0.tar.gz -
Subject digest:
0cfb2ea35cc447aeb7d2b1f9d8cb46cb3dbdf11014dd32780a2ee0638eda69ab - Sigstore transparency entry: 299760636
- Sigstore integration time:
-
Permalink:
mawildoer/groupie@bf50b4a701290bb9a8e6e66ecb0600072ee24070 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/mawildoer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@bf50b4a701290bb9a8e6e66ecb0600072ee24070 -
Trigger Event:
release
-
Statement type:
File details
Details for the file groupie-0.1.0-py3-none-any.whl.
File metadata
- Download URL: groupie-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2749385dcfb500108da891ae22c957778cd45cf3ffffee324429731b543ebcf0
|
|
| MD5 |
6bdc3a0869121979efc85fe46d6da924
|
|
| BLAKE2b-256 |
667df3054671857f65ef92071a8b32192e65c799f49d7225b8387d85b255ba08
|
Provenance
The following attestation bundles were made for groupie-0.1.0-py3-none-any.whl:
Publisher:
release.yml on mawildoer/groupie
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
groupie-0.1.0-py3-none-any.whl -
Subject digest:
2749385dcfb500108da891ae22c957778cd45cf3ffffee324429731b543ebcf0 - Sigstore transparency entry: 299760656
- Sigstore integration time:
-
Permalink:
mawildoer/groupie@bf50b4a701290bb9a8e6e66ecb0600072ee24070 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/mawildoer
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@bf50b4a701290bb9a8e6e66ecb0600072ee24070 -
Trigger Event:
release
-
Statement type: