Rust-like error handling in Python, with type-safety in mind.
Project description
poltergeist
Rust-like error handling in Python, with type-safety in mind.
Installation
pip install poltergeist
Examples
Use the @poltergeist
decorator on any function:
from poltergeist import poltergeist
# Handle an exception type potentially raised within the function
@poltergeist(OSError)
def read_text(path: str) -> str:
with open(path) as f:
return f.read()
# Returns an object of type Result[str, OSError]
result = read_text("my_file.txt")
Or wrap errors manually:
from poltergeist import Result, Ok, Err
# Equivalent to the decorated function above
def read_text(path: str) -> Result[str, OSError]:
try:
with open(path) as f:
return Ok(f.read())
except OSError as e:
return Err(e)
Then handle the result in a type-safe way:
# Get the Ok value or re-raise the Err exception
content: str = result.unwrap()
# Get the Ok value or a default if it's an Err
content: str = result.unwrap_or("lorem ipsum")
content: str | None = result.unwrap_or()
# Get the Ok value or compute it from the exception
content: str = result.unwrap_or_else(lambda e: f"The exception was: {e}")
# Get the Err exception or None if it's an Ok
err: OSError | None = result.err()
# Handle the result using structural pattern matching
match result:
case Ok(content):
print("Text in upper:", content.upper())
case Err(FileNotFoundError() as e):
print("File not found:", e.filename)
It's also possible to wrap multiple exception types with the decorator:
@poltergeist(OSError, UnicodeDecodeError)
def read_text(path: str) -> str:
with open(path) as f:
return f.read()
Or manually:
def read_text(path: str) -> Result[str, OSError | UnicodeDecodeError]:
try:
with open(path) as f:
return Ok(f.read())
except (OSError, UnicodeDecodeError) as e:
return Err(e)
Contributing
Set up the project using Poetry:
poetry install
Format the code:
make lint
Run tests:
make test
Check for typing and format issues:
make check
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
poltergeist-0.7.0.tar.gz
(4.0 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.7.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8f2c23d8d5d34bc377912a0a74fd52bf1f251de7c56ff9e933a5d01d148c39e9 |
|
MD5 | 93d16bb33eb97f0fd47d32d59c8d81bd |
|
BLAKE2b-256 | c0a2a8dc8957add5e2bbc21bf3d3e774ba6ed6698d651747a5cd379d49d6dc8e |