Created
September 5, 2023 05:34
-
-
Save ldub/8b1726f46c832842af5a7362247b512b to your computer and use it in GitHub Desktop.
Python Reference Model
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
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