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.
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.0.tar.gz
(3.0 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6e936c5bbc051136a63c6c8b381aadb8cb80d10e10f6386230435929cdd6d583 |
|
MD5 | 44fe0988a9177ebc4aebce52e0996cc5 |
|
BLAKE2b-256 | 6ddeecb33ddbad1c396450127f1baa585bcdaa388a6e5c8df0c4073b1c2fa9d5 |