Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions lru-cache-python/README.md
Original file line number Diff line number Diff line change
@@ -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 <kbd>Ctrl</kbd>+<kbd>C</kbd>:

```console
(venv) $ python monitor.py
(venv) $ python monitor_cached.py
```
21 changes: 21 additions & 0 deletions lru-cache-python/caching.py
Original file line number Diff line number Diff line change
@@ -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/")
38 changes: 38 additions & 0 deletions lru-cache-python/monitor.py
Original file line number Diff line number Diff line change
@@ -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")
61 changes: 61 additions & 0 deletions lru-cache-python/monitor_cached.py
Original file line number Diff line number Diff line change
@@ -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")
2 changes: 2 additions & 0 deletions lru-cache-python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
feedparser==6.0.14
requests==2.34.2
38 changes: 38 additions & 0 deletions lru-cache-python/stairs.py
Original file line number Diff line number Diff line change
@@ -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)}")
36 changes: 36 additions & 0 deletions lru-cache-python/stairs_cache_info.py
Original file line number Diff line number Diff line change
@@ -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())
40 changes: 40 additions & 0 deletions lru-cache-python/stairs_lru_cache.py
Original file line number Diff line number Diff line change
@@ -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)}")
21 changes: 21 additions & 0 deletions lru-cache-python/timed_lru_cache.py
Original file line number Diff line number Diff line change
@@ -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
Loading