-
Notifications
You must be signed in to change notification settings - Fork 0
/
python_tricks.py
471 lines (329 loc) · 7.54 KB
/
python_tricks.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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# Simple comma, be this guy:
names = [
'Alice',
'Bob',
'Dilbert',
]
# Not this guy:
names = [
'Alice',
'Bob',
'Dilbert'
]
# When reviewing changes you'll be thankful
# Use of assertions
TEST_PRODUCT = {'price': 1000, 'name': 'book'}
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price'], f'The discount is not correct: {discount}.'
return price
# Assertion won't raise since it considers it a tuple
assert (1 == 2, 'This should fail')
# Context managers
with open('hello.txt', 'w') as f:
f.write('Hello world!')
# Internally it is equivalent to:
f = open('hello.txt', 'w')
try:
f.write('Hello world!')
finally:
f.close()
# Write your own:
class ManagedFile:
def __init__(self, name):
self._name = name
self.file = None
def __enter__(self):
self.file = open(self._name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with ManagedFile('hello.txt') as f:
f.write('Hello world!')
"""
_var # Internal/private use. Either method attribute or method
var_ # Name equal to reserved word, for instance: 'class_'
__var # Avoids naming conflict in subclasses.
__var__ # Special use: __init__, __exit__, __str__, ...
_ # Temporary on insignificant variable
"""
class MyClass():
def __init__(self, class_, subclass):
self._class = class_
self._subclass = subclass
def count(self):
for _ in range(10):
self._my_print()
def _my_print(self):
print(f'{self._class}.{self._subclass}: Hello world!')
name = 'Bob'
# String formatting
# 1. "Old style"
'Hello, %s' % name
# 2. "New style"
'Hello, {}'.format(name)
'Hello, {name}'.format(name=name)
# 3. Literal string interpolation (Python 3.6+)
f'Hello, {name}!'
# 4. Template strings
from string import Template
t = Template('Hey, $name!')
t.substitute(name=name)
# Functions
# Functions are objects
def yell(text):
return text.upper() + '!'
yell('hello')
> 'HELLO!'
bark = yell
bark('woof')
> 'WOOF!'
bark.__name__
> 'yell'
# Functions can be stored in data structures.
funcs = [bark, str.lower, str.capitalize]
for f in functs:
print(f('hey'))
> 'HEY!'
> 'hey'
> 'Hey'
# Functions can be passed to other functions!
def greet(func):
greeting = func('Hi, I am a Python program')
print(greeting)
greet(bark)
> 'HI, I AM A PYTHON PROGRAM!'
# Functions can be nested.
def speak(text):
def whisper(t):
return t.lower() + '...'
return whisper(text)
# Functions can capture local state.
def make_adder(n):
def add(x):
return x + n
return add
plus_3 = make_adder(3)
plus_5 = make_adder(5)
plus_3(4)
> 7
plus_4(4)
> 9
# Objects can behave like functions.
class Adder():
def __init__(self, n):
self._n = n
def __call__(self, x):
return self._n + x
plus_3 = Adder(3)
plus_3(4)
> 7
# Lambdas
add = lambda x, y: x + y
add(5, 3)
> 8
(lambda x, y: x + y)(5, 3)
> 8
# Real use
tuples = [
(1, 'd'),
(2, 'b'),
(4, 'a'),
(3, 'c'),
]
sorted(tuples, key=lambda x: x[1])
[(4, 'a'), (2, 'b'), (3, 'c'), (1, 'd')]
# Harmful
list(filter(lambda x: x % 2 == 0, range(16)))
# Better
[x for x in range(16) if x % 2 == 0]
# Decorators
def uppercase(func):
def wrapper():
original_result = func()
modified_result = original_result.upper()
return modified_result
return wrapper
@uppercase
def greet():
return 'Hello!'
greet()
> 'HELLO!'
def strong(func):
def wrapper()
return '<strong>' + func() + '</strong>'
return wrapper
def emphasis(func):
def wrapper()
return '<em>' + func() + '</em>'
return wrapper
@strong
@emphasis
def greet():
return 'Hello!'
greet('Hello!')
> '<strong><em>Hello!</em></strong>'
def proxy(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def foo(required, *args, **kwargs):
print(required)
if args:
print(args)
if kwargs:
print(kwargs)
foo()
> TypeError:
> foo() missing 1 required positional arg: 'required'
foo('hello')
> 'hello'
foo('hello', 1, 2, 3)
> 'hello'
> (1, 2, 3)
foo('hello', 1, 2, 3, key1='value', key2=999)
> 'hello'
> (1, 2, 3)
> {'key1': 'value', 'key2': 999}
# Argument unpacking
def print_vector(x, y, z):
print(f'<{x}, {y}, {z}>')
print_vector(0, 1, 0)
tuple_vec = (1, 0, 1)
list_vec = [1, 0, 1]
print_vector(
tuple_vec[0],
tuple_vec[1],
tuple_vec[2],
)
> '<1, 0, 1>'
print_vector(*tuple_vec)
> '<1, 0, 1>'
print_vector(*list_vec)
> '<1, 0, 1>'
# "is" vs "=="
a = [1, 2, 3]
b = a
a == b
> True
a is b
> True
c = list(a)
a == c
> True
a is c
> False
# repr and str
class Car:
def __init__(self, color, km):
self._color = color
self._km = km
def __str__(self):
return f'{self._color} car with {self._km} km.'
def __repr__(self):
return f'Car({self._color}, {self._km})'
my_car = Car('red', 1000)
str(my_car)
> 'red car with 1000 km.'
repr(my_car)
> 'Car(red, 1000)'
# Exceptions
def validate(name):
if len(name) < 10:
raise ValueError(f'Name too short: {name}')
validate('joe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in validate
ValueError
class NameTooShortError(ValueError):
pass
def validate(name):
if len(name) < 10:
raise NameTooShortError(name)
validate('joe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in validate
NameTooShortError: joe
# Cloning
new_list = list(original_list)
new_dict = dict(original_dict)
new_set = set(original_set)
original = [[1, 2, 3], [4, 5, 5]]
copy = list(original)
copy.append('test')
copy
> [[1, 2, 3], [4, 5, 5], 'test']
original
> [[1, 2, 3], [4, 5, 5]]
copy[0][0] = 'X'
copy
> [['X', 2, 3], [4, 5, 5], 'test']
original
> [['X', 2, 3], [4, 5, 5]]
# Cloning part 2
import copy
original = [[1, 2, 3], [4, 5, 5]]
copy_shallow = copy.copy(original)
copy_deep = copy.deepcopy(original)
copy_shallow.append('test')
original
> [[1, 2, 3], [4, 5, 5]]
copy_shallow
> [[1, 2, 3], [4, 5, 5], 'test']
copy_deep
> [[1, 2, 3], [4, 5, 5]]
copy_shallow[0][0] = 'X'
copy_shallow
> [['X', 2, 3], [4, 5, 5], 'test']
original
> [['X', 2, 3], [4, 5, 5]]
copy_deep
> [[1, 2, 3], [4, 5, 5]]
copy_deep[0][0] = 'Y'
copy_deep
> [['Y', 2, 3], [4, 5, 5]]
copy_shallow
> [['X', 2, 3], [4, 5, 5], 'test']
original
> [['X', 2, 3], [4, 5, 5]]
# Abstract classes
class Base:
def foo(self):
raise NotImplementedError()
def bar(self):
raise NotImplementedError()
class Concrete(Base):
def foo(self):
return 'foo() called'
# We forgot to implement bar :O!
c = Concrete()
c.foo()
> 'foo() called'
c.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in bar
NotImplementedError
import abc
class Base(metaclass=abc.ABCMeta):
@abc.abstractmethod
def foo(self):
pass
@abc.abstractmethod
def bar(self):
pass
class Concrete(Base):
def foo(self):
pass
# We forgot to implement bar, again :/
b = Base()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Base with abstract methods bar, foo
c = Concrete()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Concrete with abstract methods bar