Skip to content

Commit

Permalink
Update README as_result and do notation sections (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
francium authored Dec 5, 2023
1 parent 1e99c05 commit 911651d
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ To save memory, both the ``Ok`` and ``Err`` classes are ‘slotted’,
i.e. they define ``__slots__``. This means assigning arbitrary
attributes to instances will raise ``AttributeError``.


``as_result`` Decorator
-----------------------

The ``as_result()`` decorator can be used to quickly turn ‘normal’
functions into ``Result`` returning ones by specifying one or more
exception types:
Expand Down Expand Up @@ -340,24 +344,27 @@ unconventional syntax (without the usual ``@``):
print(res.value)


Do notation: syntactic sugar for a sequence of ``and_then()`` calls.
Much like the equivalent in Rust or Haskell, but with different syntax.
Instead of ``x <- Ok(1)`` we write ``for x in Ok(1)``.
Since the syntax is generator-based, the final result must be the first line,
not the last.
Do notation
-----------

Do notation is syntactic sugar for a sequence of ``and_then()`` calls. Much
like the equivalent in Rust or Haskell, but with different syntax. Instead of
``x <- Ok(1)`` we write ``for x in Ok(1)``. Since the syntax is
generator-based, the final result must be the first line, not the last.

.. sourcecode:: python


>>> final_result: Result[float, int] = do(
Ok(len(x) + int(y) + 0.5)
for x in Ok("hello")
for y in Ok(True)
)
final_result: Result[float, int] = do(
Ok(len(x) + int(y) + 0.5)
for x in Ok("hello")
for y in Ok(True)
)

NOTE: If you exclude the type annotation e.g. ``Result[float, int]``
your type checker might be unable to infer the return type.
To avoid an error, you might need to help it with the type hint.
Note that if you exclude the type annotation, ``final_result: Result[float,
int] = ...``, your type checker may be unable to infer the return type. To
avoid an errors or warnings from your type checker, you should add a type hint
when using the ``do`` function.

This is similar to Rust's `m! macro <https://docs.rs/do-notation/latest/do_notation/>`_:

Expand Down

0 comments on commit 911651d

Please sign in to comment.