Skip to content

Instantly share code, notes, and snippets.

@eduardofcgo
Created November 23, 2021 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduardofcgo/293298c0dab44a5d6f04e17e67e4fd20 to your computer and use it in GitHub Desktop.
Save eduardofcgo/293298c0dab44a5d6f04e17e67e4fd20 to your computer and use it in GitHub Desktop.
cached iterator python
from collections.abc import Iterator
class _CachedIterator(Iterator):
def __init__(self, iterator):
self.iterator = iterator
self.cache = []
self.cached = False
def __iter__(self):
if not self.cached:
return self
else:
return iter(self.cache)
def __next__(self):
try:
current = next(self.iterator)
self.cache.append(current)
return current
except StopIteration as e:
self.cached = True
raise e
def cache(iterator):
return _CachedIterator(iterator)
def cached(func):
@wraps(func)
def cached_func(*args, **kwargs):
return cache(func(*args, **kwargs))
return cached_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment