Created
January 3, 2020 14:55
-
-
Save brezniczky/234b0ce5017744f66d3d3b8a6ad5d94f to your computer and use it in GitHub Desktop.
Demonstration of how the Python lru_cache perhaps isn't necessarily efficient by default
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Depending on the scenario, lru_cache() in functools may lead to inadvertent or | |
at least unexpected cache misses. | |
""" | |
from functools import lru_cache | |
eval_count = 0 | |
@lru_cache(maxsize=128) | |
def cached_fun(x): | |
global eval_count | |
eval_count += 1 | |
return 2 * x | |
cached_fun(2) | |
assert eval_count == 1 | |
cached_fun(2) | |
assert eval_count == 1 | |
cached_fun(x=2) | |
# this would fail: identical values passed in as keyword | |
# arguments are considered different from them defined via | |
# the positional route :S | |
# assert eval_count == 1 | |
assert eval_count == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment