Skip to content

Commit 3400850

Browse files
authored
Merge pull request #802 from AnswerDotAI/mapa
Add async mapping utilities: mapa and maybe_aiter
2 parents 2c1d1d6 + c3b204d commit 3400850

3 files changed

Lines changed: 250 additions & 171 deletions

File tree

fastcore/_modidx.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -818,7 +818,9 @@
818818
'fastcore.xtras.loads_multi': ('xtras.html#loads_multi', 'fastcore/xtras.py'),
819819
'fastcore.xtras.local2utc': ('xtras.html#local2utc', 'fastcore/xtras.py'),
820820
'fastcore.xtras.make_nullable': ('xtras.html#make_nullable', 'fastcore/xtras.py'),
821+
'fastcore.xtras.mapa': ('xtras.html#mapa', 'fastcore/xtras.py'),
821822
'fastcore.xtras.mapped': ('xtras.html#mapped', 'fastcore/xtras.py'),
823+
'fastcore.xtras.maybe_aiter': ('xtras.html#maybe_aiter', 'fastcore/xtras.py'),
822824
'fastcore.xtras.maybe_await': ('xtras.html#maybe_await', 'fastcore/xtras.py'),
823825
'fastcore.xtras.maybe_open': ('xtras.html#maybe_open', 'fastcore/xtras.py'),
824826
'fastcore.xtras.mkdir': ('xtras.html#mkdir', 'fastcore/xtras.py'),

fastcore/xtras.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,8 @@
1313
'stringfmt_names', 'PartialFormatter', 'partial_format', 'truncstr', 'utc2local', 'local2utc', 'trace',
1414
'modified_env', 'ContextManagers', 'shufflish', 'console_help', 'hl_md', 'type2str', 'dataclass_src',
1515
'Unset', 'nullable_dc', 'make_nullable', 'flexiclass', 'asdict', 'vars_pub', 'is_typeddict', 'is_namedtuple',
16-
'CachedIter', 'CachedAwaitable', 'reawaitable', 'is_async_callable', 'maybe_await', 'noopa', 'flexicache',
17-
'time_policy', 'mtime_policy', 'timed_cache']
18-
19-
# %% ../nbs/03_xtras.ipynb #ecd054a6
20-
#| export
21-
16+
'CachedIter', 'CachedAwaitable', 'reawaitable', 'is_async_callable', 'maybe_await', 'maybe_aiter', 'mapa',
17+
'noopa', 'flexicache', 'time_policy', 'mtime_policy', 'timed_cache']
2218

2319
# %% ../nbs/03_xtras.ipynb #3401d507
2420
from .imports import *
@@ -1033,6 +1029,21 @@ async def maybe_await(o):
10331029
from inspect import isawaitable
10341030
return await o if isawaitable(o) else o
10351031

1032+
# %% ../nbs/03_xtras.ipynb #985e3551
1033+
def maybe_aiter(items):
1034+
"Convert `items` to async generator if needed, and return it"
1035+
if hasattr(items, '__aiter__'): return items
1036+
else:
1037+
async def f(items):
1038+
for item in items: yield item
1039+
return f(items)
1040+
1041+
1042+
# %% ../nbs/03_xtras.ipynb #371d5196
1043+
async def mapa(f, items):
1044+
from asyncio import gather
1045+
return await gather(*[maybe_await(f(o)) async for o in maybe_aiter(items)])
1046+
10361047
# %% ../nbs/03_xtras.ipynb #02f9f070
10371048
async def noopa(x=None, *args, **kwargs):
10381049
"Do nothing (async)"

0 commit comments

Comments
 (0)