Skip to content

maybe

maybe(callback)

Evaluate the callback to return a value.

Unlike Typescript, Python does not have optional chaining::

https://en.wikipedia.org/wiki/Safe_navigation_operator#Python

To simulate this we can use this function as follows::

ans = maybe(lambda: path.to.prop)  # type: ignore[union-attr]

It is ok to disable the union-attr mypy check as long as mypy is checking for no-any-return.

Parameters:

Name Type Description Default
callback Callable[[], T]

A function return a value.

required

Returns:

Type Description
T | None

The value returned by the function or None.

Source code in m/core/maybe.py
def maybe(callback: Callable[[], T]) -> T | None:
    """Evaluate the callback to return a value.

    Unlike Typescript, Python does not have optional chaining::

        https://en.wikipedia.org/wiki/Safe_navigation_operator#Python

    To simulate this we can use this function as follows::

        ans = maybe(lambda: path.to.prop)  # type: ignore[union-attr]

    It is ok to disable the `union-attr` mypy check as long as mypy is checking
    for `no-any-return`.

    Args:
        callback: A function return a value.

    Returns:
        The value returned by the function or `None`.
    """
    try:
        return callback()
    except AttributeError:
        return None

non_null(inst)

Assert that inst is not None.

Implementation taken from::

https://github.com/python/typing/issues/645#issuecomment-501057220

Parameters:

Name Type Description Default
inst T | None

A possibly null instance.

required

Returns:

Type Description
T

The same argument with the None type removed.

Source code in m/core/maybe.py
def non_null(inst: T | None) -> T:
    """Assert that `inst` is not `None`.

    Implementation taken from::

        https://github.com/python/typing/issues/645#issuecomment-501057220

    Args:
        inst: A possibly null instance.

    Returns:
        The same argument with the `None` type removed.
    """
    # The assert statement can go away with the -O flag.
    assert inst is not None  # noqa: S101
    return inst