|
13 | 13 | 'round_multiple', 'set_num_threads', 'join_path_file', 'autostart', 'EventTimer', 'stringfmt_names', |
14 | 14 | 'PartialFormatter', 'partial_format', 'utc2local', 'local2utc', 'trace', 'modified_env', 'ContextManagers', |
15 | 15 | 'shufflish', 'console_help', 'hl_md', 'type2str', 'dataclass_src', 'Unset', 'nullable_dc', 'make_nullable', |
16 | | - 'flexiclass', 'asdict', 'is_typeddict', 'is_namedtuple', 'flexicache', 'time_policy', 'mtime_policy', |
17 | | - 'timed_cache'] |
| 16 | + 'flexiclass', 'asdict', 'is_typeddict', 'is_namedtuple', 'CachedIter', 'CachedAwaitable', 'reawaitable', |
| 17 | + 'flexicache', 'time_policy', 'mtime_policy', 'timed_cache'] |
18 | 18 |
|
19 | 19 | # %% ../nbs/03_xtras.ipynb |
20 | 20 | from .imports import * |
@@ -744,6 +744,29 @@ def is_namedtuple(cls): |
744 | 744 | "`True` if `cls` is a namedtuple type" |
745 | 745 | return issubclass(cls, tuple) and hasattr(cls, '_fields') |
746 | 746 |
|
| 747 | +# %% ../nbs/03_xtras.ipynb |
| 748 | +class CachedIter: |
| 749 | + "Cache the result returned by an iterator" |
| 750 | + def __init__(self, o): self.o,self.value = o,UNSET |
| 751 | + def __iter__(self): |
| 752 | + if self.value is UNSET: self.value = yield from self.o |
| 753 | + return self.value |
| 754 | + |
| 755 | +# %% ../nbs/03_xtras.ipynb |
| 756 | +class CachedAwaitable: |
| 757 | + "Cache the result from an awaitable" |
| 758 | + def __init__(self, o): self.o,self.value = o,UNSET |
| 759 | + def __await__(self): |
| 760 | + if self.value is UNSET: self.value = yield from self.o.__await__() |
| 761 | + return self.value |
| 762 | + |
| 763 | +# %% ../nbs/03_xtras.ipynb |
| 764 | +def reawaitable(func:callable): |
| 765 | + "Wraps the result of an asynchronous function into an object which can be awaited more than once" |
| 766 | + @wraps(func) |
| 767 | + def _f(*args, **kwargs): return CachedAwaitable(func(*args, **kwargs)) |
| 768 | + return _f |
| 769 | + |
747 | 770 | # %% ../nbs/03_xtras.ipynb |
748 | 771 | def flexicache(*funcs, maxsize=128): |
749 | 772 | "Like `lru_cache`, but customisable with policy `funcs`" |
|
0 commit comments