-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecorators.py
More file actions
31 lines (25 loc) · 798 Bytes
/
Copy pathdecorators.py
File metadata and controls
31 lines (25 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# using decorators to factor-out administrative logic
# biz logic is opening a url and looking up web page
# admin logic to factor out is caching the lookup
# mixes logics and is not reusable
def web_lookup(url, saved={}):
if url in saved:
return saved[url]
page = urllib.urlopen(url).read()
saved[url] = page
return page
# BETTER:
@cache # this is lrucache, only for pure functions (not random.random, etc.)
def weblookup(url):
return urllib.urlopen(url).read()
# caching decorator - your utils libraries should be full of these
def cache(func):
saved = {}
@wraps(func)
def newfunc(*args):
if args in saved:
return newfunc(*args)
result = func(*args)
saved[args] = result
return result
return newfunc