from functools import lru_cache @lru_cache(maxsize=2) def read(key): print("compute") return key for key in ["A", "B", "A", "C", "B"]: read(key)