class defaultdict2(defaultdict):

    def __missing__(self, key):
        value = self.default_factory(key)
self[key] = value
return value

def noisy_default_with_key(key):
    print(key)
return key + 1
d = defaultdict2(noisy_default_with_key)
d[1]
d[1]
How to implement a lazy setdefault?