Skip to content

Commit

Permalink
Map async (#165)
Browse files Browse the repository at this point in the history
Continuation of #162
  • Loading branch information
francium authored Dec 23, 2023
1 parent c776db4 commit 73bfe6d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ Possible log types:

## [Unreleased]

- `[added]` Add `map_async` for async functions (#165)
- `[fixed]` Add `do_async()` to handle edge case in `do()` involving multiple inlined awaits (#149)

- `[added]` Add support for Python 3.12 (#157)

## [0.15.0] - 2023-12-04
Expand Down
16 changes: 16 additions & 0 deletions src/result/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ def map(self, op: Callable[[T], U]) -> Ok[U]:
"""
return Ok(op(self._value))

async def map_async(
self, op: Callable[[T], Awaitable[U]]
) -> Ok[U]:
"""
The contained result is `Ok`, so return the result of `op` with the
original value passed in
"""
return Ok(await op(self._value))

def map_or(self, default: object, op: Callable[[T], U]) -> U:
"""
The contained result is `Ok`, so return the original value mapped to a new
Expand Down Expand Up @@ -340,6 +349,13 @@ def map(self, op: object) -> Err[E]:
"""
return self

async def map_async(self, op: object) -> Err[E]:
"""
The contained result is `Ok`, so return the result of `op` with the
original value passed in
"""
return self

def map_or(self, default: U, op: object) -> U:
"""
Return the default value
Expand Down
19 changes: 19 additions & 0 deletions tests/test_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,25 @@ async def test_and_then_async() -> None:
).err() == 3


@pytest.mark.asyncio
async def test_map_async() -> None:
async def str_upper_async(s: str) -> str:
return s.upper()

async def str_async(x: int) -> str:
return str(x)

o = Ok('yay')
n = Err('nay')
assert (await o.map_async(str_upper_async)).ok() == 'YAY'
assert (await n.map_async(str_upper_async)).err() == 'nay'

num = Ok(3)
errnum = Err(2)
assert (await num.map_async(str_async)).ok() == '3'
assert (await errnum.map_async(str_async)).err() == 2


def test_or_else() -> None:
assert Ok(2).or_else(sq).or_else(sq).ok() == 2
assert Ok(2).or_else(to_err).or_else(sq).ok() == 2
Expand Down

0 comments on commit 73bfe6d

Please sign in to comment.