Cache history of mutable dictionary

2023/09/05

The Python dictionary type is mutable, meaning that it can be modified after it is created. In the case below, a dictionary d is added to a cache list, and any changes made to d result in updates to both the old and new d entries in the cache.

d = {0: 0}
cache = []
cache.append(d)
print(cache) # [{0: 0}]

d[0] = 1
cache.append(d)
print(cache) # [{0: 1}, {0: 1}]

An alternative approach, aside from using collections.namedtuple or a types.MappingProxyType, is to bypass the dictionary and store items directly in the cache.

cache = {t: None for t in range(2)}
cache[0] = {0:0}
print(cache) # {0: {0: 0}, 1: None}

cache[1] = {0:1}
print(cache) # {0: {0: 1}, 1: {0: 1}}