Skip to main content

Experimental Rust-like error handling in Python, with type-safety in mind.

Project description

poltergeist

pypi versions

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


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)

Uploaded Source

Built Distribution

poltergeist-0.2.1-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page