Skip to main content

Option and Try monads implementation in pure Python code

Project description

Option and Try Monads for Python

Functional programming utilities inspired by Scala.


Option Monad

Option represents a value that may or may not exist.

  • Some(value) — a present value
  • Nothing — absence of a value

This eliminates manual None checks and enables functional pipelines.

Creating Options

Option.of(10)      # Some(10)
Option.of(None)    # Nothing

Properties

Property Some Nothing
is_defined True False
is_empty False True

Methods

map(fn)

Transforms the wrapped value if present.

Option.of(10).map(lambda x: x * 2)   # Some(20)
Option.of(None).map(lambda x: x * 2) # Nothing

flat_map(fn)

Chaining operations that return Option.

def safe_div(a, b):
    return Option.of(a / b if b != 0 else None)

Option.of(10).flat_map(lambda x: safe_div(x, 2)) # Some(5)

filter(predicate)

Keeps the value only if it satisfies the predicate.

Option.of(10).filter(lambda x: x > 5)  # Some(10)
Option.of(3).filter(lambda x: x > 5)   # Nothing

get_or_else(default)

Option.of(None).get_or_else(99)  # 99

fold(default, mapping_fn)

Useful for extraction.

Option.of(20).fold(0, lambda x: x * 2)  # 40

or_else(other_option)

Option.of(None).or_else(Option.of(5))  # Some(5)

flatten()

Option.of(Option.of(10)).flatten()  # Some(10)

Iteration

for value in Option.of(10):
    print(value)   # 10

Decorator: @to_option

Converts function output into Option.

@to_option
def compute(x):
    return x * 2

compute(10)  # Some(20)

Try Monad

Try models computations that may throw exceptions.

  • Success(value)
  • Failure(exception)

It removes the need for try/except in functional code.

Creating Try Values

Try.of(lambda: 10 / 2)  # Success(5.0)
Try.of(lambda: 10 / 0)  # Failure(ZeroDivisionError)

Properties

Property Success Failure
is_success True False
is_failure False True

Methods

map(fn)

Only applied if successful.

Try.of(lambda: 5).map(lambda x: x + 1)   # Success(6)
Try.of(lambda: 1/0).map(lambda x: x + 1) # Failure(...)

flat_map(fn)

Chaining computations that return Try.

def parse_int(s: str):
    return Try.of(lambda: int(s))

Try.of(lambda: "123").flat_map(parse_int)  # Success(123)

filter(predicate)

Try.of(lambda: 10).filter(lambda x: x > 5)  # Success(10)
Try.of(lambda: 3).filter(lambda x: x > 5)   # Failure(ValueError)

get_or_else(default)

Try.of(lambda: 10/0).get_or_else(99)  # 99

or_else(default_try)

Try.of(lambda: 10/0).or_else(Success(5))  # Success(5)

fold(default_fn, mapping_fn)

Try.of(lambda: 10 / 0).fold(
    default=lambda ex: f"Error: {ex}",
    mapping_fn=lambda x: x * 2
)
# "Error: division by zero"

flatten()

Try.of(lambda: Success(10)).flatten()  # Success(10)

Converting to Option

Try.of(lambda: 10).to_option()      # Some(10)
Try.of(lambda: 1/0).to_option()     # Nothing

Iteration

for v in Try.of(lambda: 10):
    print(v)

Decorator: @to_try

Automatically wraps exceptions into a Try.

@to_try
def divide(a, b):
    return a / b

divide(10, 2)  # Success(5.0)
divide(10, 0)  # Failure(ZeroDivisionError)

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

monadspy-1.0.2.tar.gz (10.5 kB view details)

Uploaded Source

Built Distribution

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

monadspy-1.0.2-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file monadspy-1.0.2.tar.gz.

File metadata

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

File hashes

Hashes for monadspy-1.0.2.tar.gz
Algorithm Hash digest
SHA256 3b88f8e8ef6b9c6d79c69553096f91ad0fc227125ffec66c0bd495f2bb97aa7d
MD5 efc6977351e1a2a48c70da2e44aaacbe
BLAKE2b-256 e99dc9a86c9cdea4e7758b23d299776cb1a98a799dbf82229c26f1cc3c0bf820

See more details on using hashes here.

Provenance

The following attestation bundles were made for monadspy-1.0.2.tar.gz:

Publisher: python-publish.yml on Lorenzo-Gardini/monadspy

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

File details

Details for the file monadspy-1.0.2-py3-none-any.whl.

File metadata

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

File hashes

Hashes for monadspy-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 504c9f52e1353caeea0b592485a3568ab1683b01808250c7d01026a553ed3d12
MD5 be66491efd323f6c6826507e07cd7d3d
BLAKE2b-256 77aeff1648999b89d3559cbd1d8e8af01e5e4bc5d1c7df7bbd8a83de053cc857

See more details on using hashes here.

Provenance

The following attestation bundles were made for monadspy-1.0.2-py3-none-any.whl:

Publisher: python-publish.yml on Lorenzo-Gardini/monadspy

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