-
Notifications
You must be signed in to change notification settings - Fork 0
/
clarity.py
70 lines (40 loc) · 1.01 KB
/
clarity.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Bad
twitter_search('@obama', False, 20, True)
# Better, with keyword arguments
twitter_search('@obama', retweets=False, numtweets=20, popular=True)
# Bad
doctest.testmod()
# returns (0, 4)
# Better
doctest.testmod()
# returns TestResults(failed=0, attempted=4)
# where TestResults = namedTuple('TestResults', ['failed', 'attempted'])
# Bad, mixes business/administrative logic 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
def web_lookup(url):
return urllib.urlopen(url).read()
# Bad
f = open('data.txt')
try:
data = f.read()
finally:
f.close()
# Better, context automatically deals with file closing
with open('data.txt') as f:
data = f.read()
# Bad
old_context = getcontext().copy()
getcontext().prec = 50
print Decimal(355) / Decimal(113)
setcontext(old_context)
# Better
with localcontext(Context(prec=50)):
print Decimal(355) / Decimal(113)
#