|
| 1 | +.. _methods: |
| 2 | + |
| 3 | +Methods |
| 4 | +========= |
| 5 | + |
| 6 | +The following useful methods can be used to interact with interfaces. |
| 7 | + |
| 8 | +cond |
| 9 | +---- |
| 10 | + |
| 11 | +Reduce the boilerplate when choosing paths with ``DiverseFailableN``. |
| 12 | +Think of this method as a functional ``if`` alternative |
| 13 | +for successful or failed types. |
| 14 | + |
| 15 | +So, this code: |
| 16 | + |
| 17 | +.. code:: python |
| 18 | +
|
| 19 | + >>> from returns.result import Failure, Result, Success |
| 20 | +
|
| 21 | + >>> def is_numeric(string: str) -> Result[str, str]: |
| 22 | + ... if string.isnumeric(): |
| 23 | + ... return Success('It is a number') |
| 24 | + ... return Failure('It is not a number') |
| 25 | +
|
| 26 | +Can be replaced with this: |
| 27 | + |
| 28 | +.. code:: python |
| 29 | +
|
| 30 | + >>> from returns.methods import cond |
| 31 | + >>> from returns.result import Failure, Result, Success |
| 32 | +
|
| 33 | + >>> def is_numeric(string: str) -> Result[str, str]: |
| 34 | + ... return cond( |
| 35 | + ... Result, |
| 36 | + ... string.isnumeric(), |
| 37 | + ... 'It is a number', |
| 38 | + ... 'It is not a number', |
| 39 | + ... ) |
| 40 | +
|
| 41 | + >>> assert is_numeric('42') == Success('It is a number') |
| 42 | + >>> assert is_numeric('text') == Failure('It is not a number') |
| 43 | +
|
| 44 | +Why is it helpful? Because ``cond`` can be easily added |
| 45 | +into a :ref:`pipelines` of functions. |
| 46 | + |
| 47 | + |
| 48 | +unwrap_or_failure |
| 49 | +----------------- |
| 50 | + |
| 51 | +Unwraps either a successful or failed value. |
| 52 | + |
| 53 | +.. code:: python |
| 54 | +
|
| 55 | + >>> from returns.io import IO, IOSuccess, IOFailure |
| 56 | + >>> from returns.methods import unwrap_or_failure |
| 57 | +
|
| 58 | + >>> assert unwrap_or_failure(IOSuccess(1)) == IO(1) |
| 59 | + >>> assert unwrap_or_failure(IOFailure('a')) == IO('a') |
| 60 | +
|
| 61 | +Useful when you have a ``ResultLike`` value with correctly handled error value, |
| 62 | +for example with :func:`~returns.pointfree.bimap.bimap`. |
| 63 | +Here's a full example: |
| 64 | + |
| 65 | +.. code:: python |
| 66 | +
|
| 67 | + >>> from returns.result import Failure, Result, Success |
| 68 | + >>> from returns.methods import unwrap_or_failure |
| 69 | + >>> from returns.pointfree import bimap |
| 70 | +
|
| 71 | + >>> instance: Result[int, str] = Success(1) |
| 72 | + >>> error_handled = bimap(lambda inr: inr + 1, lambda _: 0)(instance) |
| 73 | + >>> assert isinstance(unwrap_or_failure(error_handled), int) |
| 74 | +
|
| 75 | +
|
| 76 | +API Reference |
| 77 | +------------- |
| 78 | + |
| 79 | +.. autofunction:: returns.methods.cond |
| 80 | + |
| 81 | +.. autofunction:: returns.methods.unwrap_or_failure |
0 commit comments