Skip to content

Commit 73bfe6d

Browse files
authored
Map async (#165)
Continuation of #162
1 parent c776db4 commit 73bfe6d

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

CHANGELOG.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ Possible log types:
1313

1414
## [Unreleased]
1515

16+
- `[added]` Add `map_async` for async functions (#165)
1617
- `[fixed]` Add `do_async()` to handle edge case in `do()` involving multiple inlined awaits (#149)
17-
1818
- `[added]` Add support for Python 3.12 (#157)
1919

2020
## [0.15.0] - 2023-12-04

src/result/result.py

+16
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,15 @@ def map(self, op: Callable[[T], U]) -> Ok[U]:
151151
"""
152152
return Ok(op(self._value))
153153

154+
async def map_async(
155+
self, op: Callable[[T], Awaitable[U]]
156+
) -> Ok[U]:
157+
"""
158+
The contained result is `Ok`, so return the result of `op` with the
159+
original value passed in
160+
"""
161+
return Ok(await op(self._value))
162+
154163
def map_or(self, default: object, op: Callable[[T], U]) -> U:
155164
"""
156165
The contained result is `Ok`, so return the original value mapped to a new
@@ -340,6 +349,13 @@ def map(self, op: object) -> Err[E]:
340349
"""
341350
return self
342351

352+
async def map_async(self, op: object) -> Err[E]:
353+
"""
354+
The contained result is `Ok`, so return the result of `op` with the
355+
original value passed in
356+
"""
357+
return self
358+
343359
def map_or(self, default: U, op: object) -> U:
344360
"""
345361
Return the default value

tests/test_result.py

+19
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,25 @@ async def test_and_then_async() -> None:
225225
).err() == 3
226226

227227

228+
@pytest.mark.asyncio
229+
async def test_map_async() -> None:
230+
async def str_upper_async(s: str) -> str:
231+
return s.upper()
232+
233+
async def str_async(x: int) -> str:
234+
return str(x)
235+
236+
o = Ok('yay')
237+
n = Err('nay')
238+
assert (await o.map_async(str_upper_async)).ok() == 'YAY'
239+
assert (await n.map_async(str_upper_async)).err() == 'nay'
240+
241+
num = Ok(3)
242+
errnum = Err(2)
243+
assert (await num.map_async(str_async)).ok() == '3'
244+
assert (await errnum.map_async(str_async)).err() == 2
245+
246+
228247
def test_or_else() -> None:
229248
assert Ok(2).or_else(sq).or_else(sq).ok() == 2
230249
assert Ok(2).or_else(to_err).or_else(sq).ok() == 2

0 commit comments

Comments
 (0)