Result

class emlib.result.Result(ok, value=None, info='')[source]

Bases: Generic[_T]

A class to encapsulate the result of an operation

This is useful for operations which can either return a value or an error message.

Parameters:
  • ok (bool) – True if ok, False if failed

  • value (Optional[TypeVar(_T)]) – the value returned by the operation

  • info (str) – an error message if the operation failed

Example

from emlib.result import Result
import re
from fractions import Fraction

def parsefraction(txt: str) -> Result[Fraction]:
    match = re.match(r"([0-9]+)\/([1-9][0-9]*)", txt)
    if not match:
        return Result.Fail(f"Could not parse '{txt}' as fraction")
    num = int(match.group(1))
    den = int(match.group(2))
    return Result.Ok(Fraction(num, den))

if fraction := parsefraction("4/5"):
    print(f"Fraction ok: {fraction.value})  # prints 'Fraction(4, 5)'

Typing

To make typing analysis work better it is possible to indicate the kind of value wrapped by the Result class. See the return type declared in parsefraction in the example above

Attributes Summary

failed

True if operation failed

Methods Summary

Fail(info[, value])

Create a Result object for a failed operation.

Ok([value])

Create a Result object for a successful operation.

Attributes Documentation

failed

True if operation failed

Methods Documentation

classmethod Fail(info, value=None)[source]

Create a Result object for a failed operation.

Return type:

Result

classmethod Ok(value=None)[source]

Create a Result object for a successful operation.

Return type:

Result