Skip to content

Instantly share code, notes, and snippets.

@gyli
Last active November 30, 2022 20:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gyli/9b50bb8537069b4e154fec41a4b5995a to your computer and use it in GitHub Desktop.
Save gyli/9b50bb8537069b4e154fec41a4b5995a to your computer and use it in GitHub Desktop.
Lazy Dict in Python
# Lazy dict allows storing function and argument pairs when initializing the dictionary,
# it calculates the value only when fetching it.
# In this examole, if the key starts with '#', it would accept a (function, args) tuple as value and
# returns the calculated result when fetching the values.
from collections.abc import Mapping
class LazyDict(Mapping):
def __init__(self, *args, **kw):
self._raw_dict = dict(*args, **kw)
def __getitem__(self, key):
if key.startswith('#'):
func, arg = self._raw_dict.__getitem__(key)
return func(arg)
return self._raw_dict.__getitem__(key)
def __iter__(self):
return iter(self._raw_dict)
def __len__(self):
return len(self._raw_dict)
# Initialize a lazy dict
d = LazyDict(
{
'#1': (lambda x: x + 1, 0),
'#2': (lambda x: x + 2, 0),
'#3': (lambda x: x + 3, 0)
}
)
# Let's try to fetch first two values
count = 0
for index, value in d.items():
print(d[index])
count += 1
if count >= 1:
break
# Output:
# 1
# 2
# Function for "#3" doesn't run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment