Skip to main content

Rust-like traits and patterns for Python

Project description

Rython 🐍🦀

Rython is a Python framework that brings the power and safety of Rust's trait system and functional programming patterns to Python. It provides a robust way to define interfaces, implement them for existing types, and leverage monadic error handling and iterator adapters.

✨ Features

  • Traits & Implementations: Define strict interfaces (@trait) and implement them for any type (@impl), even built-ins like int or str.
  • Introspection: Check if an object implements a trait at runtime.
  • Derive Macros: Automatically generate implementations for common traits (e.g., @derive(Debug, Default)).
  • Monads: strictly typed Option[T] and Result[T, E] for safer control flow.
  • Iterators: Rust-style lazy iterators (RyIterator) with chainable methods like .map(), .filter(), .collect().
  • Type Safety: Fully typed and compatible with static analysis tools like mypy and pyrefly.

📦 Installation

Rython is managed with uv. You can install it or add it to your project:

# Using uv
uv add rython

# Or install locally for development
git clone https://github.com/WeiNyn/rython.git
cd rython
uv sync

🚀 Quick Start

Defining and Implementing Traits

To define a trait, decorate a class with @trait and inherit from Trait. This ensures full compatibility with static type checkers.

from rython import trait, impl, Trait

# 1. Define a Trait
@trait
class Speak(Trait):
    def speak(self) -> str:
        raise NotImplementedError

class Dog:
    pass

class Cat:
    pass

# 2. Implement the Trait for types
@impl(Speak, for_type=Dog)
class DogSpeak:
    def speak(self) -> str:
        return "Woof!"

@impl(Speak, for_type=Cat)
class CatSpeak:
    def speak(self) -> str:
        return "Meow!"

# 3. Use the Trait
def make_it_speak(obj):
    # Syntax: Trait(object).method()
    print(Speak(obj).speak())

make_it_speak(Dog()) # Output: Woof!
make_it_speak(Cat()) # Output: Meow!

Derive Macros

Automatically implement standard traits for your classes.

from rython import derive, Debug, Default

@derive(Debug, Default)
class Config:
    host: str = "localhost"
    port: int = 8080

c = Default(Config).default()
print(Debug(c).fmt()) 
# Output: Config(host='localhost', port=8080)

Monads: Option & Result

Replace None checks and exceptions with safe, expressive types.

from rython import Option, Some, Nothing, Result, Ok, Err

# Option
def divide(a, b) -> Option[float]:
    if b == 0:
        return Nothing
    return Some(a / b)

result = divide(10, 2).map(lambda x: x * 2).unwrap_or(0.0)
print(result) # 10.0

# Result
def parse_int(s: str) -> Result[int, str]:
    try:
        return Ok(int(s))
    except ValueError:
        return Err(f"Invalid integer: {s}")

match parse_int("42"):
    case Ok(val): print(f"Parsed: {val}")
    case Err(e): print(f"Error: {e}")

Iterators

Chainable, lazy transformations on collections.

from rython import RyIterator

data = [1, 2, 3, 4, 5]
squared_evens = (
    RyIterator(data)
    .filter(lambda x: x % 2 == 0)
    .map(lambda x: x * x)
    .collect(list)
)
print(squared_evens) # [4, 16]

🛠️ Development

This project uses uv for dependency management and just as a command runner.

# Install dependencies
uv sync

# Run all checks (lint, format, types, tests)
just check

# Run tests only
just test

# Fix linting issues
just lint

📄 License

MIT

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

rlython-0.1.0.tar.gz (11.6 kB view details)

Uploaded Source

Built Distribution

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

rlython-0.1.0-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: rlython-0.1.0.tar.gz
  • Upload date:
  • Size: 11.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.22 {"installer":{"name":"uv","version":"0.9.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for rlython-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6f75eda17b94047a25e63d4ccec6cfb6b8c9046e790f36f97771e5e610e24574
MD5 1dae30757aacdbf571a57bc23f99b8f5
BLAKE2b-256 aeb7d3770b494e4dd562d75334652d28415fa39db43d6dff8a6c479fce13d592

See more details on using hashes here.

File details

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

File metadata

  • Download URL: rlython-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.22 {"installer":{"name":"uv","version":"0.9.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for rlython-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7c7663b3eef2014944f4f6790a3be793bfb39422ca7269b2e94516043e3f3879
MD5 ae867cc891cc5db7a22f35c9a72269ef
BLAKE2b-256 a8949c656308603a35c1865609f2ded6c102adc8cfa15a7cf3d85e778f67d746

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