Skip to content

Commit d2eba76

Browse files
committed
Refs #83
1 parent e8c6f6f commit d2eba76

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

docs/pages/container.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ You can have a look at the suggested ``mypy``
273273
`configuration <https://github.com/dry-python/returns/blob/master/setup.cfg>`_
274274
in our own repository.
275275

276+
.. _composition:
276277

277278
Composition
278279
-----------
@@ -281,8 +282,8 @@ You can and should compose different containers together.
281282
Here's the full table of compositions that make sense:
282283

283284
- ``IO[Result[A, B]]`` ✅
285+
- ``Result[IO[A], B]`` ✅
284286
- ``IO[IO[A]]`` 🚫
285-
- ``Result[IO[A], B]`` 🚫
286287
- ``Result[A, IO[A]]`` 🚫
287288
- ``Result[Result[A, B], C]`` 🚫
288289
- ``Result[A, Result[B, C]]`` 🚫

docs/pages/io.rst

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,51 @@ If the value is fetched, input, received, selected, than use ``IO`` container.
188188

189189
Most web applications are just covered with ``IO``.
190190

191+
What is the difference between IO[Result[A, B]] and Result[IO[A], B]?
192+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193+
194+
As we state in :ref:`Composition docs <composition>`
195+
we allow to compose different containers together.
196+
197+
That's where this question raises:
198+
should I apply ``IO`` to all ``Result`` or only to the value part?
199+
200+
Short answer: we prefer ``IO[Result[A, B]]``
201+
and sticking to the single version allows better composition.
202+
203+
Long answer. Let's see these two examples:
204+
205+
.. code:: python
206+
207+
from returns.io import IO, impure
208+
from returns.result import Result, safe
209+
210+
def get_user_age() -> Result[IO[int], ValueError]:
211+
# Safe, but impure operation:
212+
prompt: IO[str] = impure(input)('What's your age?')
213+
214+
# Pure, but unsafe operation:
215+
return safe(int)(prompt)
216+
217+
In this case we return `Result[IO[int], ValueError]`,
218+
since ``IO`` operation is safe and cannot throw.
219+
220+
.. code:: python
221+
222+
import requests
223+
224+
from returns.io import IO, impure
225+
from returns.result import Result, safe
226+
227+
@impure
228+
@safe
229+
def get_user_age() -> IO[Result[int, Exception]]:
230+
# We ask another micro-service, it is impure and can fail:
231+
return requests.get('https://...').json()
232+
233+
In this case the whole result is marked as impure.
234+
Since its failures are impure as well.
235+
191236
Why can't we unwrap values or use @pipeline with IO?
192237
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193238

0 commit comments

Comments
 (0)