Skip to main content

Make your python code a little bit rustier.

Project description

🦀 Carcinize 🦀

Born to write Rust but forced to use Python to survive? Learned Rust for fun and now all the missing language features are driving you crazy? Want to look really p̶r̶e̶t̶e̶n̶t̶i̶o̶u̶s̶ cool in front of your coworkers?

Try Carcinization! 🦀 🦀 🦀

What's up with the name?

Carcinization is the tendency for convergent evolution of many species to eventually become crabs, or as Lancelot Alexander Borradaile put it: "the many attempts of Nature to evolve a crab".

As I have fully drunk the Rust kool-aid, I am now fully committed to the idea that everything should be a crab. Including Python.

Another equally valid interpretation is it's a verb form of "carcinogen", because using this library will give your Python projects cancer. Who's to say which is correct?

Installation

Install with uv:

uv add carcinize

No I won't add examples for pip, poetry, or god forbid conda. It's 2026, grow up and use uv.

Requires Python 3.12+.

Features

Result

A type representing either success (Ok) or failure (Err). Errors must be Exception subclasses, so unwrap() raises the actual error.

from carcinize import Ok, Err, Result

def divide(a: int, b: int) -> Result[float, ZeroDivisionError]:
    if b == 0:
        return Err(ZeroDivisionError("cannot divide by zero"))
    return Ok(a / b)

# Pattern matching
match divide(10, 2):
    case Ok(value):
        print(f"Result: {value}")
    case Err(error):
        print(f"Error: {error}")

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

Methods: is_ok(), is_err(), ok(), err(), unwrap(), unwrap_err(), expect(), expect_err(), unwrap_or(), unwrap_or_else(), map(), map_err(), map_or(), map_or_else(), and_then(), or_else()

Option

A type representing an optional value (Some or Nothing). We use Nothing instead of None to avoid confusion with Python's None.

from carcinize import Some, Nothing, Option

def find_user(id: int) -> Option[str]:
    users = {1: "alice", 2: "bob"}
    if id in users:
        return Some(users[id])
    return Nothing()

# Pattern matching
match find_user(1):
    case Some(name):
        print(f"Found: {name}")
    case Nothing():
        print("User not found")

# Method chaining
name = find_user(1).map(str.upper).unwrap_or("anonymous")

Methods: is_some(), is_nothing(), unwrap(), expect(), unwrap_or(), unwrap_or_else(), map(), map_or(), map_or_else(), and_then(), or_else(), filter(), ok_or(), ok_or_else(), zip()

Struct / MutStruct

Pydantic-based structs with Rust-like semantics. Extra fields are forbidden, strict validation is enabled, and fields are validated on assignment.

from carcinize import Struct, MutStruct

# Immutable (frozen, hashable)
class Point(Struct):
    x: int
    y: int

p = Point(x=1, y=2)
# p.x = 3  # Error: frozen

# Mutable
class Config(MutStruct):
    host: str
    port: int = 8080

config = Config(host="localhost")
config.port = 9000  # OK

# Safe parsing with Result
match Config.try_from({"host": "localhost"}):
    case Ok(cfg):
        print(cfg.host)
    case Err(validation_error):
        print(validation_error)

Methods: try_from(), clone(), as_dict(), as_json()

Struct also enforces deep immutability - nested mutable objects are rejected at construction time.

Note: try_from() accepts either a dict or a JSON string. Other types return Err(TypeError).

Iter

Fluent iterator with chainable combinators, inspired by Rust's Iterator trait.

from carcinize import Iter

# Chain transformations
result = (
    Iter([1, 2, 3, 4, 5])
    .filter(lambda x: x > 2)
    .map(lambda x: x * 2)
    .collect_list()
)  # [6, 8, 10]

# Find with Option
first_even = Iter([1, 3, 4, 5]).find(lambda x: x % 2 == 0)  # Some(4)

# Fold/reduce
total = Iter([1, 2, 3]).fold(0, lambda acc, x: acc + x)  # 6

Transformations: map(), filter(), filter_map(), flat_map(), flatten(), inspect()

Slicing: take(), skip(), take_while(), skip_while(), step_by()

Combining: chain(), zip(), zip_longest(), enumerate(), interleave()

Folding: fold(), reduce(), sum(), product()

Searching: find(), find_map(), position(), any(), all(), count(), min(), max()

Collecting: collect_list(), collect_set(), collect_dict(), collect_string(), partition(), group_by()

Accessing: first(), last(), nth()

Sorting: sorted(), sorted_by()

Deduplication: unique(), unique_by()

Lazy / OnceCell

Thread-safe lazy initialization primitives.

from carcinize import Lazy, OnceCell

# Lazy - computed on first access
expensive_config = Lazy(lambda: load_config_from_disk())
# ... nothing computed yet ...
config = expensive_config.get()  # computed once, cached forever

# OnceCell - write exactly once
cell: OnceCell[int] = OnceCell()
cell.get()      # Nothing
cell.set(42)    # Ok(None)
cell.get()      # Some(42)
cell.set(100)   # Err(OnceCellAlreadyInitializedError)

Both are thread-safe and use double-checked locking for performance.

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

carcinize-0.1.1.tar.gz (12.3 kB view details)

Uploaded Source

Built Distribution

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

carcinize-0.1.1-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file carcinize-0.1.1.tar.gz.

File metadata

  • Download URL: carcinize-0.1.1.tar.gz
  • Upload date:
  • Size: 12.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for carcinize-0.1.1.tar.gz
Algorithm Hash digest
SHA256 a5fa00f770e8d1010b3b3b1ef883ce2ac4b9a6ab34964b16b63d8712caee33f2
MD5 08ef352a2132097d57d093c7d8144e8c
BLAKE2b-256 090806cc46fc97b9d4a608269bb33d82909bea6a2a49db4d3c713a5505f36b87

See more details on using hashes here.

Provenance

The following attestation bundles were made for carcinize-0.1.1.tar.gz:

Publisher: publish.yml on Ron-Leizrowice/carcinize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file carcinize-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: carcinize-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for carcinize-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e07f40dbcfa4eddeb84bd882776d093aa86db01076389f1d974df78a6b69dbf0
MD5 62038942d2135cf8827badd595f313db
BLAKE2b-256 62187c79ea9b720b9ca3371708f9339a96f86be1c7013fca2f5df7887dbd73b9

See more details on using hashes here.

Provenance

The following attestation bundles were made for carcinize-0.1.1-py3-none-any.whl:

Publisher: publish.yml on Ron-Leizrowice/carcinize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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