Giter VIP home page Giter VIP logo

poltergeist's Introduction

poltergeist

pypi versions

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

Installation

pip install poltergeist

Examples

Use the @catch decorator on any function:

from poltergeist import catch

# Handle an exception type potentially raised within the function
@catch(OSError)
def read_text(path: str) -> str:
    with open(path) as f:
        return f.read()

# Returns an object of type Result[str, OSError]
result = read_text("my_file.txt")

Or wrap errors manually:

from poltergeist import Result, Ok, Err

# Equivalent to the decorated function above
def read_text(path: str) -> Result[str, OSError]:
    try:
        with open(path) as f:
            return Ok(f.read())
    except OSError as e:
        return Err(e)

Then handle the result in a type-safe way:

# Get the Ok value or re-raise the Err exception
content: str = result.unwrap()

# Get the Ok value or a default if it's an Err
content: str = result.unwrap_or("lorem ipsum")
content: str | None = result.unwrap_or()

# Get the Ok value or compute it from the exception
content: str = result.unwrap_or_else(lambda e: f"The exception was: {e}")

# Get the Err exception or None if it's an Ok
err: OSError | None = result.err()

# Handle the result using structural pattern matching
match result:
    case Ok(content):
        print("Text in upper:", content.upper())
    case Err(FileNotFoundError() as e):
        print("File not found:", e.filename)

It's also possible to wrap multiple exception types with the decorator:

@catch(OSError, UnicodeDecodeError)
def read_text(path: str) -> str:
    with open(path) as f:
        return f.read()

Or manually:

def read_text(path: str) -> Result[str, OSError | UnicodeDecodeError]:
    try:
        with open(path) as f:
            return Ok(f.read())
    except (OSError, UnicodeDecodeError) as e:
        return Err(e)

There is also an async-compatible decorator:

from poltergeist import catch_async

@catch_async(OSError)
async def read_text(path: str) -> str:
    with open(path) as f:
        return f.read()

# Returns an object of type Result[str, OSError]
result = await read_text("my_file.txt")

Contributing

Set up the project using Poetry:

poetry install

Format the code:

make lint

Run tests:

make test

Check for typing and format issues:

make check

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.