diff --git a/lru-cache-python/README.md b/lru-cache-python/README.md new file mode 100644 index 0000000000..05d3c1e98a --- /dev/null +++ b/lru-cache-python/README.md @@ -0,0 +1,38 @@ +# Caching in Python Using the LRU Cache Strategy + +This folder contains the sample code for the Real Python tutorial [Caching in Python Using the LRU Cache Strategy](https://realpython.com/lru-cache-python/). + +## Setup + +You need Python 3.10 or later. Create and activate a virtual environment, then install the pinned dependencies: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +## Usage + +Cache articles in a dictionary: + +```console +(venv) $ python caching.py +``` + +Count the ways to climb a staircase, first with plain recursion and then with `@lru_cache`: + +```console +(venv) $ python stairs.py +(venv) $ python stairs_lru_cache.py +(venv) $ python stairs_cache_info.py +``` + +The uncached `stairs.py` takes a while to finish because it times thirty calls to `steps_to(30)`. + +Monitor the Real Python feed without and with the time-based `@timed_lru_cache` decorator from `timed_lru_cache.py`. Both scripts run until you press Ctrl+C: + +```console +(venv) $ python monitor.py +(venv) $ python monitor_cached.py +``` diff --git a/lru-cache-python/caching.py b/lru-cache-python/caching.py new file mode 100644 index 0000000000..400acc33f8 --- /dev/null +++ b/lru-cache-python/caching.py @@ -0,0 +1,21 @@ +import requests + +cache = dict() + + +def get_article_from_server(url): + print("Fetching article from server...") + response = requests.get(url) + return response.text + + +def get_article(url): + print("Getting article...") + if url not in cache: + cache[url] = get_article_from_server(url) + + return cache[url] + + +get_article("https://realpython.com/sorting-algorithms-python/") +get_article("https://realpython.com/sorting-algorithms-python/") diff --git a/lru-cache-python/monitor.py b/lru-cache-python/monitor.py new file mode 100644 index 0000000000..ee7e804f59 --- /dev/null +++ b/lru-cache-python/monitor.py @@ -0,0 +1,38 @@ +import feedparser +import requests +import ssl +import time + +if hasattr(ssl, "_create_unverified_context"): + ssl._create_default_https_context = ssl._create_unverified_context + + +def get_article_from_server(url): + print("Fetching article from server...") + response = requests.get(url) + return response.text + + +def monitor(url): + maxlen = 45 + while True: + print("\nChecking feed...") + feed = feedparser.parse(url) + + for entry in feed.entries[:5]: + if "python" in entry.title.lower(): + truncated_title = ( + entry.title[:maxlen] + "..." + if len(entry.title) > maxlen + else entry.title + ) + print( + "Match found:", + truncated_title, + len(get_article_from_server(entry.link)), + ) + + time.sleep(5) + + +monitor("https://realpython.com/atom.xml") diff --git a/lru-cache-python/monitor_cached.py b/lru-cache-python/monitor_cached.py new file mode 100644 index 0000000000..3e5bf960d9 --- /dev/null +++ b/lru-cache-python/monitor_cached.py @@ -0,0 +1,61 @@ +import feedparser +import requests +import ssl +import time + +from functools import lru_cache, wraps +from datetime import datetime, timedelta, timezone + +if hasattr(ssl, "_create_unverified_context"): + ssl._create_default_https_context = ssl._create_unverified_context + + +def timed_lru_cache(seconds: int, maxsize: int = 128): + def wrapper_cache(func): + func = lru_cache(maxsize=maxsize)(func) + func.lifetime = timedelta(seconds=seconds) + func.expiration = datetime.now(timezone.utc) + func.lifetime + + @wraps(func) + def wrapped_func(*args, **kwargs): + if datetime.now(timezone.utc) >= func.expiration: + func.cache_clear() + func.expiration = datetime.now(timezone.utc) + func.lifetime + + return func(*args, **kwargs) + + return wrapped_func + + return wrapper_cache + + +@timed_lru_cache(10) +def get_article_from_server(url): + print("Fetching article from server...") + response = requests.get(url) + return response.text + + +def monitor(url): + maxlen = 45 + while True: + print("\nChecking feed...") + feed = feedparser.parse(url) + + for entry in feed.entries[:5]: + if "python" in entry.title.lower(): + truncated_title = ( + entry.title[:maxlen] + "..." + if len(entry.title) > maxlen + else entry.title + ) + print( + "Match found:", + truncated_title, + len(get_article_from_server(entry.link)), + ) + + time.sleep(5) + + +monitor("https://realpython.com/atom.xml") diff --git a/lru-cache-python/requirements.txt b/lru-cache-python/requirements.txt new file mode 100644 index 0000000000..1b4d37f558 --- /dev/null +++ b/lru-cache-python/requirements.txt @@ -0,0 +1,2 @@ +feedparser==6.0.14 +requests==2.34.2 diff --git a/lru-cache-python/stairs.py b/lru-cache-python/stairs.py new file mode 100644 index 0000000000..596a000bf7 --- /dev/null +++ b/lru-cache-python/stairs.py @@ -0,0 +1,38 @@ +from timeit import repeat + + +def steps_to(stair): + if stair == 1: + # You can reach the first stair with only a single step + # from the floor. + return 1 + elif stair == 2: + # You can reach the second stair by jumping from the + # floor with a single two-stair hop or by jumping a single + # stair a couple of times. + return 2 + elif stair == 3: + # You can reach the third stair using four possible + # combinations: + # 1. Jumping all the way from the floor + # 2. Jumping two stairs, then one + # 3. Jumping one stair, then two + # 4. Jumping one stair three times + return 4 + else: + # You can reach your current stair from three different places: + # 1. From three stairs down + # 2. From two stairs down + # 2. From one stair down + # + # If you add up the number of ways of getting to those + # those three positions, then you should have your solution. + return steps_to(stair - 3) + steps_to(stair - 2) + steps_to(stair - 1) + + +print(steps_to(30)) + +setup_code = "from __main__ import steps_to" +stmt = "steps_to(30)" +times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) +print(f"Minimum execution time: {min(times)}") diff --git a/lru-cache-python/stairs_cache_info.py b/lru-cache-python/stairs_cache_info.py new file mode 100644 index 0000000000..d8cda4c205 --- /dev/null +++ b/lru-cache-python/stairs_cache_info.py @@ -0,0 +1,36 @@ +from functools import lru_cache + + +@lru_cache(maxsize=16) +def steps_to(stair): + if stair == 1: + # You can reach the first stair with only a single step + # from the floor. + return 1 + elif stair == 2: + # You can reach the second stair by jumping from the + # floor with a single two-stair hop or by jumping a single + # stair a couple of times. + return 2 + elif stair == 3: + # You can reach the third stair using four possible + # combinations: + # 1. Jumping all the way from the floor + # 2. Jumping two stairs, then one + # 3. Jumping one stair, then two + # 4. Jumping one stair three times + return 4 + else: + # You can reach your current stair from three different places: + # 1. From three stairs down + # 2. From two stairs down + # 2. From one stair down + # + # If you add up the number of ways of getting to those + # those three positions, then you should have your solution. + return steps_to(stair - 3) + steps_to(stair - 2) + steps_to(stair - 1) + + +print(steps_to(30)) + +print(steps_to.cache_info()) diff --git a/lru-cache-python/stairs_lru_cache.py b/lru-cache-python/stairs_lru_cache.py new file mode 100644 index 0000000000..78a6162251 --- /dev/null +++ b/lru-cache-python/stairs_lru_cache.py @@ -0,0 +1,40 @@ +from functools import lru_cache +from timeit import repeat + + +@lru_cache +def steps_to(stair): + if stair == 1: + # You can reach the first stair with only a single step + # from the floor. + return 1 + elif stair == 2: + # You can reach the second stair by jumping from the + # floor with a single two-stair hop or by jumping a single + # stair a couple of times. + return 2 + elif stair == 3: + # You can reach the third stair using four possible + # combinations: + # 1. Jumping all the way from the floor + # 2. Jumping two stairs, then one + # 3. Jumping one stair, then two + # 4. Jumping one stair three times + return 4 + else: + # You can reach your current stair from three different places: + # 1. From three stairs down + # 2. From two stairs down + # 2. From one stair down + # + # If you add up the number of ways of getting to those + # those three positions, then you should have your solution. + return steps_to(stair - 3) + steps_to(stair - 2) + steps_to(stair - 1) + + +print(steps_to(30)) + +setup_code = "from __main__ import steps_to" +stmt = "steps_to(30)" +times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) +print(f"Minimum execution time: {min(times)}") diff --git a/lru-cache-python/timed_lru_cache.py b/lru-cache-python/timed_lru_cache.py new file mode 100644 index 0000000000..d815a861a4 --- /dev/null +++ b/lru-cache-python/timed_lru_cache.py @@ -0,0 +1,21 @@ +from functools import lru_cache, wraps +from datetime import datetime, timedelta, timezone + + +def timed_lru_cache(seconds: int, maxsize: int = 128): + def wrapper_cache(func): + func = lru_cache(maxsize=maxsize)(func) + func.lifetime = timedelta(seconds=seconds) + func.expiration = datetime.now(timezone.utc) + func.lifetime + + @wraps(func) + def wrapped_func(*args, **kwargs): + if datetime.now(timezone.utc) >= func.expiration: + func.cache_clear() + func.expiration = datetime.now(timezone.utc) + func.lifetime + + return func(*args, **kwargs) + + return wrapped_func + + return wrapper_cache