Notes and exercises for learning design patterns
Add caching to an adapter that generates many derived objects.
Exercise 3 created windows every time the adapter was instantiated.
That is correct, but wasteful when the same series and settings are adapted repeatedly.
The forecasting team now trains for many epochs.
Each epoch needs the same training windows:
for epoch in range(10):
windows = SeriesToWindowAdapter(series, window_size=24)
train(windows)
If the raw series did not change, generating the same windows again is unnecessary.
So you will create a cached adapter.
Open exercise4.py and implement CachedSeriesToWindowAdapter.
The adapter should:
window_size and horizon,__iter__,__len__,clear_cache() for tests.Use this key:
(series.sensor_id, series.version, window_size, horizon)
The key should include everything that affects the generated windows.
For this exercise, assume version changes whenever the raw series changes.
CachedSeriesToWindowAdapter.clear_cache()
adapter1 = CachedSeriesToWindowAdapter(series, window_size=3)
adapter2 = CachedSeriesToWindowAdapter(series, window_size=3)
assert CachedSeriesToWindowAdapter.generation_count == 1
assert list(adapter1) == list(adapter2)
The second adapter should reuse the cached windows.
python exercise4.py