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 provided @poltergeist
decorator on any function:
from pathlib import Path
from poltergeist import Err, Ok, Result, poltergeist
# Wrap a function to handle a concrete exception type (Exception by default)
@poltergeist(error=OSError)
def read_text(path: Path) -> str:
return path.read_text()
# Now the function returns an object of type Result[str, OSError]
result = read_text(Path("test.txt"))
Or wrap errors manually:
def read_text(path: Path) -> Result[str, OSError]:
try:
return Ok(path.read_text())
except OSError as e:
return Err(e)
Then handle the result:
# Get the contained Ok value or raise the contained Err exception
content = result.unwrap()
# Get the contained Ok value or a default value
content = result.unwrap_or("default text")
content = result.unwrap_or() # default None
# Get the contained Ok value or compute it from a callable
content = result.unwrap_or_else(lambda e: f"The exception was: {e}")
# Get the contained Err exception or None
err = result.err()
# Handle errors using structural pattern matching
match result:
case Ok(content):
print("File content in upper case:", content.upper())
case Err(e):
match e:
case FileNotFoundError():
print("File not found:", e.filename)
case PermissionError():
print("Permission error:", e.errno)
case _:
raise 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.6.0.tar.gz
(4.0 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.6.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 77464954cf4d64e80aecd60b00f7f757a319e8ba04520b004be0edd0fbe42907 |
|
MD5 | e16b3174b6db730afce5cc86789eb27b |
|
BLAKE2b-256 | 3add389704c48f5754c861180087d8c6465d9484ac3d6b6445b61ce99492df24 |