-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathnew_patterns.py
More file actions
438 lines (280 loc) · 6.76 KB
/
new_patterns.py
File metadata and controls
438 lines (280 loc) · 6.76 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""
Using an unpythonic loop:
Instead of counting over an index and retrieving the corresponding index element within the for
loop, you should use enumerate to retrieve the index and list element simultaneously.
"""
l = [1,2,3]
#Bad
for i in range(0,len(list)):
le = l[i]
print i,le
#Good
for i,le in enumerate(l):
print i,le
"""
Returning more than one variable type from function call
A function call should return only one type of variable. Example: If a function is supposed to
return a list, do not return None if an error occurs or some condition is unmet. Instead, raise
an exception.
Why this is bad:
If a function that is supposed to return a given type (e.g. list, tuple, dict) suddenly returns
something else (e.g. None) the caller of that function will always need to check the type of the
return value before proceeding. This makes for confusing and complex code. If the function is unable
to produce the supposed return value it is better to raise an exception that can be caught by the caller instead.
"""
#Bad
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
return None
return r
res = filter_for_foo(["bar","foo","faz"])
if res is not None:
#continue processing
pass
#Good
def filter_for_foo(l):
r = [e for e in l if e.find("foo") != -1]
if not check_some_critical_condition(r):
raise SomeException("critical condition unmet!")
return r
try:
res = filter_for_foo(["bar","foo","faz"])
#continue processing
except SomeException:
#handle exception
"""
The loop may never terminate
The given loop does not modify anything that impacts the loop condition and does not call 'break', 'return' or 'yield' explicitly
, which may lead to an infinite loop.
"""
#example:
i = 0
while i < 10:
do_something()
#we forget to increment i
"""
Not using .items() to iterate over a list of key/value pairs of a dictionary.
"""
#Bad
d = {'foo' : 1,'bar' : 2}
for key in d:
value = d[key]
print "%s = %d" % (key,value)
#Good
for key,value in d.items():
print "%s = %d" % (key,value)
"""
Not using zip() to iterate over a pair of lists
"""
#Bad
l1 = [1,2,3]
l2 = [4,5,6]
for i in range(l1):
l1v = l1[i]
l2v = l2[i]
print l1v,l2v
#Good
for l1v,l2v in zip(l1,l2):
print l1v,l2v
"""
Using "key in list" to check if a key is contained in a list.
This is not an error but inefficient, since the list search is O(n). If possible, a set or dictionary
should be used instead.
Note: Since the conversion of the list to a set is an O(n) operation, it should ideally be done only once when generating the list.
"""
#Bad:
l = [1,2,3,4]
if 3 in l:
pass
#Good
s = set(l)
if 3 in s:
pass
"""
Not using 'else' where appropriate in a loop.
'else' can be used in a loop context to execute code in case the loop does not get terminated by a 'break' statement.
See here for more details:
https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
"""
#Bad
found = False
l = [1,2,3]
for i in l:
if i == 4:
found = True
break
if not found:
#not found...
pass
#Good
for i in l:
if i == 4:
break
else:
#not found...
"""
Not using .setdefault() where appropriate.
setdefault can be used to initialize a dictionary value with a default.
https://docs.python.org/2/library/stdtypes.html#dict.setdefault
For usage examples see here:
http://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method
"""
#Bad
d = {}
if not 'foo' in d:
d['foo'] = []
d['foo'].append('bar')
#Good
d = {}
foo = d.setdefault('foo',[])
foo.append(bar)
"""
Not using .get() to return a default value from a dict
https://docs.python.org/2/library/stdtypes.html#dict.get
"""
#Bad
d = {'foo' : 'bar'}
foo = 'default'
if 'foo' in d:
foo = d['foo']
#Good
foo = d.get('foo','default')
"""
Using map/filter where a list comprehension would be possible
"""
#Bad:
values = [1,2,3]
doubled_values = map(lambda x:x*2,values)
#Good
doubled_values = [x*2 for x in values]
#Bad
filtered_values = filter(lambda x:True if x < 2 else False,values)
#Good
filtered_values = [x for x in values if x < 2]
"""
Not using defaultdict where appropriate
"""
#Bad
d = {}
if not 'count' in d:
d['count'] = 0
d['count']+=1
#Good
from collections import defaultdict
d = defaultdict(lambda :0)
d['count']+=1
"""
Not using a namedtuple when returning more than one value from a function
Named tuples can be used anywhere where normal tuples are acceptable, but their values can be accessed
through their name in addition to their index, which makes code more verbose and easier to read.
https://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields
"""
#Bad
def foo():
#....
return -1,"not found"
status_code,message = foo()
print status_code,message
#Good
from collections import namedtuple
def foo():
#...
return_args = namedtuple('return_args',['status_code','message'])
return return_args(-1,"not found")
ra = foo()
print ra.status_code,ra.message
"""
Not using explicit unpacking of sequencing
Python supports unpacking of lists, tuples and dicts.
"""
#Bad
l = [1,"foo","bar"]
l0 = l[0]
l1 = l[1]
l2 = l[2]
#Good
l0,l1,l2 = l
"""
Not using unpacking for updating multiple values at once
"""
#Bad
x = 1
y = 2
_t = x
x = y+2
y = x-4
#Good
x = 1
y = 2
x,y = y+2,x-4
"""
Not using 'with' to open files
"""
#Bad
f = open("file.txt","r")
content = f.read()
f.close()
#Good
with open("file.txt","r") as input_file:
content = f.read()
"""
Asking for permission instead of forgiveness when working with files
"""
#Bad
import os
if os.path.exists("file.txt"):
os.unlink("file.txt")
#Good
import os
try:
os.unlink("file.txt")
except OSError:
pass
"""
Not using a dict comprehension where appropriate
"""
#Bad
l = [1,2,3]
d = dict([(n,n*2) for n in l])
#Good
d = {n : n*2 for n in l}
"""
Using string concatenation instead of formatting
"""
#Bad
n_errors = 10
s = "there were "+str(n_errors)+" errors."
#Good
s = "there were %d errors." % n_errors
"""
Putting type information in the variable name (Hungarian notation)
"""
#Bad
intN = 4
strFoo = "bar"
#Good
n = 4
foo = "bar"
"""
Implementing Java-style getters and setters instead of using properties.
http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters
"""
#Bad
class Foo(object):
def __init__(a):
self._a = a
def get_a(self):
return a
def set_a(self,value):
self._a = value
#Good
class Foo(object):
def __init__(a):
self._a = a
@property
def a(self):
return self._a
@a.setter
def a(self,value):
self._a = value