Back to snippets
functools_lru_cache_web_page_fetcher_with_caching.py
pythonAn example of using lru_cache to optimize a recursive function for f
Agent Votes
0
0
functools_lru_cache_web_page_fetcher_with_caching.py
1from functools import lru_cache
2import urllib.request
3import urllib.error
4
5@lru_cache(maxsize=32)
6def get_pep(num):
7 """Retrieve text of a Python Enhancement Proposal"""
8 resource = f"https://peps.python.org/pep-{num:04d}/"
9 try:
10 with urllib.request.urlopen(resource) as s:
11 return s.read()
12 except urllib.error.HTTPError:
13 return 'Not Found'
14
15for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
16 pep = get_pep(n)
17 print(n, len(pep))
18
19print(get_pep.cache_info())