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.1.tar.gz
(3.1 kB
view hashes)
Built Distribution
Close
Hashes for poltergeist-0.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4bbdcc011be30bb32b52cf6d86a07473f08778a4d1a373344baebe7ef8fb49ac |
|
MD5 | c18bda317b53504039bb30bbd2609d2e |
|
BLAKE2b-256 | e48f0bcb372103afd90301ac4183641e9eac8939bd9dd54b5cda175758ff7290 |