Skip to main content

Functional programming patterns for Python

Project description

better-py

Functional programming patterns for Python - pragmatic, type-safe, and developer-friendly.

CI Coverage PyPI Python License

✨ Features

Monads & Functional Types

  • Maybe[T] - Handle optional values safely
  • Result<T, E> - Explicit error handling
  • Either<L, R> - Two-value alternatives
  • Validation<T, E> - Accumulate validation errors
  • And more: Try, IO, Reader, Writer, State, Task, etc.

Functional Collections

  • MappableList[T] - List with functional operations
  • ImmutableDict[K, V] - Safe immutable dictionaries
  • LazySequence[T] - Lazy evaluation sequences
  • BidirectionalMap[K, V] - Two-way lookups

Function Utilities

  • curry(f) - Incremental argument application
  • compose(f, g) - Function composition
  • pipe(value, f, g) - Left-to-right pipelines
  • partial(f, ...) - Fix function arguments

OOP-First Design

  • Protocol-based (like collections.abc)
  • Generic types with full type hints
  • Method chaining and fluent APIs
  • Modern Python patterns (dataclasses, protocols, etc.)

🚀 Quick Start

from better_py import Maybe, Result, pipe

# Maybe: Safe optional handling
user = Maybe.from_value(get_user(id))
name = user.map(lambda u: u.name).unwrap_or_else(lambda: "Guest")

# Result: Explicit error handling
def divide(a: int, b: int) -> Result[float, str]:
    if b == 0:
        return Result.error("Division by zero")
    return Result.ok(a / b)

result = divide(10, 2)
if result.is_ok():
    print(f"Result: {result.unwrap()}")
else:
    print(f"Error: {result.unwrap_error()}")

# Pipe: Data pipelines
result = pipe(
    data,
    validate,
    transform,
    save
)

📦 Installation

# Install from PyPI
pip install better-py

# Or with uv (recommended)
uv pip install better-py

Requirements: Python 3.11+

📚 Documentation

💡 Why better-py?

Pragmatic FP

Not academic functional programming - practical patterns that make software development easier.

Type-Safe

Full type hints with mypy strict mode. Catch errors before runtime.

OOP-First

Everything is an object. Operations are functional. Works naturally with Python.

Developer-Friendly

Clear error messages, helpful APIs, extensive documentation.

🎯 Use Cases

# REST API error handling
from better_py import Result

async def get_user(id: int) -> Result[User, Error]:
    user = await db.fetch_user(id)
    if not user:
        return Result.error(Error("User not found"))
    return Result.ok(user)

# Data validation
from better_py import Validation

email_validated = Validation.validate(email, EmailValidator())
password_validated = Validation.validate(password, PasswordValidator())

user_validation = email_validated.and_then(password_validated)
if user_validation.is_valid():
    create_user(email, password)

# Data processing pipeline
from better_py import pipe

result = pipe(
    raw_data,
    clean,
    validate,
    transform,
    load_to_db
)

🏗️ Project Status

Current Version: 0.1.0 (Alpha)

What's Working:

  • ✅ Documentation framework
  • ✅ CI/CD pipeline
  • ✅ Type system design

In Development:

  • 🔄 Core protocols (Mappable, Reducible, etc.)
  • 🔄 Monad implementations
  • 🔄 Functional collections
  • 🔄 Function utilities

Planned:

  • 📋 More monads (Writer, State, etc.)
  • 📋 Performance benchmarks
  • 📋 Integration examples (FastAPI, SQLAlchemy, etc.)

See Issues for detailed roadmap.

🤝 Contributing

Contributions are welcome! Please see CONTRIBUTING.md for details.

Quick start:

# Clone repository
git clone https://github.com/nesalia-inc/better-py.git
cd better-py

# Install with uv
uv venv && source .venv/bin/activate  # Windows: .venv\Scripts\activate
uv sync --all-extras

# Run tests
uv run pytest

# Run checks
uv run ruff check .
uv run mypy better_py

📄 License

MIT License - see LICENSE for details.

🙏 Acknowledgments

Inspired by:

📮 Contact


Made with ❤️ by nesalia-inc

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

better_py_fp-0.1.0.tar.gz (302.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

better_py_fp-0.1.0-py3-none-any.whl (46.5 kB view details)

Uploaded Python 3

File details

Details for the file better_py_fp-0.1.0.tar.gz.

File metadata

  • Download URL: better_py_fp-0.1.0.tar.gz
  • Upload date:
  • Size: 302.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for better_py_fp-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1fa4bc3324d94e927df20a93bf50748b95eb837ec6704b3082ad6f10e35e49ad
MD5 3e2f966e42cdeff9b3f744238cff3ece
BLAKE2b-256 d16e2eadbe24711842a8d081ced68bd6f840673392e8a1a77739a4f7b4168fb5

See more details on using hashes here.

File details

Details for the file better_py_fp-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: better_py_fp-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 46.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for better_py_fp-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 42c9e852ef564bcc66972e87f0998be30c5360ff85bc50b5c8bc6aa3c3645447
MD5 3b356f15a22e032ddf26ce55f22c706d
BLAKE2b-256 58f043226be8aa25d62afd3d6f97cea5395ba9b5017edc56585733935e883da6

See more details on using hashes here.

Supported by

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