Pyre Extensions

0.0.32 · active · verified Sat Apr 11

Pyre Extensions is a Python library offering type system extensions designed specifically for use with the Pyre type checker. Currently at version 0.0.32 and classified as 'Alpha' development status, it provides advanced typing constructs like `ParameterSpecification`, `none_throws`, and a type-safe `safe_json` module. Its release cadence is closely tied to the development and releases of the main Pyre type checker.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the use of `ParameterSpecification` for typing decorators that preserve function signatures, and `none_throws` for asserting non-None values. It defines a decorator `unwrap` that extracts the first item from a list returned by a function, raising an error if the list is empty. Note that Pyre would perform static analysis to ensure type safety based on these annotations.

from typing import TypeVar, Callable, List
from pyre_extensions import ParameterSpecification, none_throws

TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")

def unwrap(f: Callable[TParams, List[TReturn]]) -> Callable[TParams, TReturn]:
    """Example of a decorator using ParameterSpecification."""
    def inner(*args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
        result = f(*args, **kwargs)
        # Using none_throws for explicit Optional handling
        first_item = none_throws(result[0]) if result else None
        if first_item is None:
            raise ValueError("List must not be empty for unwrap to extract an item")
        return first_item
    return inner

@unwrap
def get_first_char_list(s: str, upper: bool = False) -> List[str]:
    chars = [c.upper() for c in s] if upper else list(s)
    return chars

@unwrap
def get_empty_list(x: int) -> List[int]:
    return []

# Example usage
print(f"First char (upper): {get_first_char_list('hello', upper=True)}")
print(f"First char (lower): {get_first_char_list('world')}")

try:
    get_empty_list(123)
except ValueError as e:
    print(f"Caught expected error for empty list: {e}")

view raw JSON →