e2fyi.utils.core.maybe

This module provides a Maybe generic class to describe an unreliable output.

Module Contents

Classes

Maybe

Maybe is a generic class used to describe an output that can potentially

e2fyi.utils.core.maybe.T
class e2fyi.utils.core.maybe.Maybe(value: Optional[T] = None, exception: BaseException = None)

Maybe is a generic class used to describe an output that can potentially fails (e.g. raise exception).

Example:

import logging

from e2fyi.utils.core import Maybe


def load_from_file(filepath: str) -> Maybe[string]:
    try:
        with open(filepath, "r") as fp:
            return Maybe(fp.read())
    except IOError as err:
        return Maybe(exception=err)

data = load_from_file("some_file.json")

# print with a default value fallback
print(data.with_default("default value"))

# print data if ok, else log exception
if data.is_ok:
    print(data)
else:
    logging.exception(data.exception)

Creates a new instance of Maybe. If an exception is provided, the Maybe value is considered to be not ok.

property is_ok(self) → bool

whether the output is generated successfully.

with_default(self, default_value: T)T

returns a default value if the outputs is not generated successfully.