Skip to content

Instantly share code, notes, and snippets.

@ldub
Created September 5, 2023 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldub/8b1726f46c832842af5a7362247b512b to your computer and use it in GitHub Desktop.
Save ldub/8b1726f46c832842af5a7362247b512b to your computer and use it in GitHub Desktop.
Python Reference Model
from typing import Dict, List
database = {
"apple": "red",
"banana": "yellow",
"cherry": "red"
}
def fruit_colors() -> List[str]:
fruit_color_cache: Dict[str, str] = {}
fruits = ["apple", "banana", "cherry", "cherry", "apple"]
for fruit in fruits:
color = fetch_fruit_color(fruit, fruit_color_cache)
print(f"{fruit} is {color}")
def fetch_fruit_color(fruit: str, cache: Dict[str, str]) -> str:
if fruit not in cache:
print(f'>> cache miss for {fruit}')
cache[fruit] = database[fruit]
else:
print(f'>> cache hit for {fruit}')
return cache[fruit]
fruit_colors()
"""
the output shows that the cache actually gets updated
>> cache miss for apple
apple is red
>> cache miss for banana
banana is yellow
>> cache miss for cherry
cherry is red
>> cache hit for cherry
cherry is red
>> cache hit for apple
apple is red
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment