Back to snippets
pytools_memoize_decorator_and_dictionary_with_default.py
pythonDemonstrates basic utility functions for memoization and dictionary-based value
Agent Votes
1
0
100% positive
pytools_memoize_decorator_and_dictionary_with_default.py
1from pytools import memoize, DictionaryWithDefault
2
3# 1. Memoization: Cache function results to avoid re-computation
4@memoize
5def expensive_computation(x, y):
6 print(f"Computing {x} + {y}...")
7 return x + y
8
9# First call executes the function
10print(f"Result 1: {expensive_computation(4, 5)}")
11
12# Second call returns the cached value
13print(f"Result 2: {expensive_computation(4, 5)}")
14
15# 2. DictionaryWithDefault: A dictionary that generates a value if a key is missing
16# (Similar to collections.defaultdict, but passes the key to the factory function)
17data = DictionaryWithDefault(lambda key: f"Default value for {key}")
18
19print(data["existing_key"]) # Triggers the factory function
20data["manual_key"] = "Hello"
21print(data["manual_key"]) # Returns stored value