Experimental Rust-like error handling in Python, with type-safety in mind.
Project description
poltergeist
Experimental 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, poltergeist
@poltergeist(OSError)
def read_text(path: Path) -> str:
return path.read_text()
# Result of type Result[str, OSError]
result = read_text(Path("test.txt"))
# Get the contained Ok value or raise the contained Err exception
content = result.unwrap()
# Get the contained Ok value or a provided default
content = result.unwrap_or("default text")
# 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):
# Type-checkers know the return type of the original function
print("File content in upper case:", content.upper())
case Err(e):
match e:
# The exception type is also known
case FileNotFoundError():
print("File not found:", e.filename)
case PermissionError():
print("Permission error:", e.errno)
case _:
raise e
You can also wrap errors yourself:
from pathlib import Path
from poltergeist import Err, Ok, Result
def read_text(path: Path) -> Result[str, FileNotFoundError]:
try:
return Ok(path.read_text())
except FileNotFoundError as e:
return Err(e)
Both of these examples pass type checking and provide in-editor autocompletion.
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.3.1.tar.gz
(3.4 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.3.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 20e5578fb146c566f7fe9a2bc29154d64ad8b5540f9a3afce77aa38038cc71c4 |
|
MD5 | fd6a58142a9b3b394bdde200409aaaaf |
|
BLAKE2b-256 | 85a4afc7a3cce9568c8cbe816aa686d22d4a29e736a4c07e283eb482e1320bd8 |