Maybe-Else

0.2.1 · active · verified Sun Apr 12

Provides a `Maybe` class as a Python implementation of null-aware operators. It allows for safe chaining of operations, attribute access, item access, and method calls on potentially `None` values, falling back to a default if `None` is encountered at any point. This helps avoid explicit `if var is not None` checks, similar to Optional/Maybe types in other languages. The library is currently at version 0.2.1, with its first and only release in November 2019.

Warnings

Install

Imports

Quickstart

The `Maybe` class wraps a value, allowing subsequent attribute, item, or method calls to be chained. If any step in the chain encounters a `None` or raises a caught exception, the entire chain short-circuits, and `else_()` returns the provided default. Otherwise, the result of the final operation is returned.

from maybe_else import Maybe

# Basic usage: providing a default for None
result1 = Maybe(None).else_("default value")
print(f"Result 1: {result1}")

# Chained operations on a non-None value
data = {'user': {'name': 'Alice', 'age': 30}}
maybe_name = Maybe(data)['user'].get('name').upper().else_('Unknown')
print(f"Maybe name: {maybe_name}")

# Chained operations on a path with None
missing_data = {'user': None}
maybe_age = Maybe(missing_data)['user'].get('age').else_(0) # 'user' is None, so default is used
print(f"Maybe age (missing user): {maybe_age}")

# Chained operations with a legitimate None as an intermediate result
def get_nullable_value(x):
    return None if x % 2 == 0 else x

result_none_output = Maybe(2).map(get_nullable_value).else_('Fallback')
print(f"Result None output (even number): {result_none_output}") # Expected: None, not 'Fallback' (see warnings)

result_non_none_output = Maybe(3).map(get_nullable_value).else_('Fallback')
print(f"Result Non-None output (odd number): {result_non_none_output}")

view raw JSON →