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 = read_text(Path("test.txt"))
# 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
# Or directly get the returned value, raising an 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.3.tar.gz
(3.2 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.2.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d99bc3fd0cb99362e33afb51c7b7191648e8ccc923043f8968d022ead8b065a7 |
|
MD5 | 0d4e5af32b4a4e68a253765a5d7f1694 |
|
BLAKE2b-256 | 9a777f1fa06320bc8f0accd7ce0e9998607bbf5c80ab8a8c6a1abd691bc181af |