better-py

Getting started

Get started with better-py, a pragmatic functional programming library for Python

Getting Started

Welcome to better-py! This guide will help you get started with the library.

Installation

Install better-py using your preferred package manager:

# Using pip
pip install better-py

# Using uv
uv add better-py

# Using poetry
poetry add better-py

Quick Overview

better-py is a pragmatic, type-safe functional programming library for Python that provides:

  • Monads: Maybe, Result, Either, Validation, and more for handling values and errors
  • Protocols: Functional behaviors like Mappable, Reducible, and Traversable
  • Immutable Collections: PersistentList, PersistentMap, and PersistentSet
  • Function Utilities: pipe, compose, curry, and other higher-order functions

Your First Monad

Here's a quick example using the Maybe monad to handle optional values:

from better_py import Some, Nothing

# Create Maybe values
maybe_value = Some(42)
empty_value = Nothing()

# Transform values
doubled = maybe_value.map(lambda x: x * 2)  # Some(84)

# Handle both cases
result = maybe_value.or_else(0)  # 42
default = empty_value.or_else(0)  # 0

print(result, default)  # Output: 42 0

Error Handling with Result

from better_py import Ok, Error

def divide(a: float, b: float):
    if b == 0:
        return Error("Cannot divide by zero")
    return Ok(a / b)

result = divide(10, 2)

if result.is_ok():
    print(f"Success: {result.value}")
else:
    print(f"Error: {result.error}")

What's Next?

On this page