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(FileNotFoundError)
def read_text(path: Path) -> str:
return path.read_text()
result = read_text(Path("test.txt"))
# Handle errors using structural pattern matching
match result:
case Ok(content):
# Type-checkers know that content is a string,
# carried over from the return type of the original function.
print("File content:", content)
case Err(e):
# The exception type is also known
print("File not found:", e.filename)
# Or directly get the returned value
# This will raise the original exception, if there was one
content = result.unwrap()
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.2.2.tar.gz
(3.1 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.2.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0dad509d7e61146b11d63655d2ade2a8785ada2f5090ebabf0ba81e45373fc5e |
|
MD5 | 26f64eae281ea8a3651cdf2adf13c236 |
|
BLAKE2b-256 | 3c8d7cbe04d3fb8773a2866c55baf0fccafe7b1ba90c90d35d2cb55bf4a1b115 |