-
Notifications
You must be signed in to change notification settings - Fork 4
/
python_cheatsheet.py
431 lines (348 loc) · 8.11 KB
/
python_cheatsheet.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
TYPES
======
True
False
None
type(var)
int(var)
str(var) # stringify
float(var)
abs(integer)
7 // 4 # floor division, truncate
round(floating, precision)
x ** y # powers
pow(x, y) # powers
STRING
======
s[i] # single char
s[start:end:step] # exclusive slice
s[::-1] # iterate backwards
s == s2
len(s)
s.lower()
s.islower()
s.capitalize() # only first word
s.count(e)
s.find(e)
s.isdigit()
s.isalpha()
s.endswith(e)
s.split(":") # returns list
s.partition(" ") # splits at first instance of sep (start, sep, end)
for char in s:
print("foo:" , foo)
"hello {}".format("world")
"hello {0} {1}".format("world", "again")
"hello {w}".format(w = "world")
"result {r:1.2f}".format(r=0.234)
"""
multi-line
{s}
""".format("string")
f"{var_name}"
f"{var_name:{padding}.{precision}}"
LIST
======
l = ['3',45,'frog']
l = list(1, 2)
len(l)
not l # empty sequences are false (check if empty)
e in l
l.index(e)
l.count(e)
l.remove(e)
l.sort() # in place
sorted(l) # returns new list
l.reverse()
min(l)
max(l)
sum(l)
"".join(l) # returns string
l[0] = 0
l.append(e)
l.insert(i, e)
l.extend(l2)
l.pop(i)
l[start:end:step] # exclusive slice
del l[0:5]
l + l
l = [e for e in iterable if cond]
l = [e if cond else e2 for e in iterable]
l = [e1*e2 for e in iterable1 for e2 in iterable2]
l2 = list(map(lambda x: x**2, l))
l2 = list(filter(lambda x: x < 0, l))
e = reduce((lambda x, y: x * y), l) # x = acc, y = curr val
DICTIONARY
======
d = {"key": "val"}
d[k] = v
k in d
del d[k]
d.keys()
d.values()
d.items()
for k,v in d.items():
d2 = {k:v for k,v in d.items()}
TUPLES #immutable
=======
t = (1,2,3)
t[0]
e in t
t.count(e)
t.index(e)
for (a,b) in t:
x,y,z = (1,2,3)
t1 + t2
SETS
=======
s = set(l)
s = set("foo") # {'f', 'o'}
s.add(e)
e in s
s.remove(e)
s.clear()
s1 - s2 # difference
s1 | s2 # union
s1 & s2 # intersection
s1 ^ s2 # opposite of intersection
s1 < s2 # subset
s2 > s2 # superset
CONDITIONALS
============
True and False (True & False)
False or True (False | True)
not True
if cond:
elif cond2:
else:
LOOPS
=======
range(start, stop, step) # generates a stream [exclusive stop]
list(range(3)) # [0,1,2]
for e in iterable:
pass #noop
continue
break
for (i, e) in enumerate(iterable, start=n): # iterate with index
for (a,b) in zip(l1, l2):
while cond:
else: # execute when while is not true
ERROR HANDLING
==========
import sys
try:
except SomeException as e:
print(sys.exc_info())
raise RuntimeError("fail") from e
else:
# runs if not excepted
finally:
MODULES
========
import math
from module import func
from MainPackage.SubPackage import sub_script
# Main Function, execute if python file called directly
if __name__ == "__main__":
pass
FUNCTIONS
=========
def func_name(name = "default"):
"""
explains func
"""
global var # change the outer variable
return name
def args_func(*args, **kwargs):
# *args = tuple of args
# **kwargs = dict of args
args_func(0,1, fruit='apple', veggie=5)
lambda (a,b): a if (a > b) else b
map(func, iterable) # func must return val
list( map(lambda x,y: x+y, list1, list2) )
filter(func, interable) # func must return T/F
reduce(lambda x,y: x+y, list1) # x = acc, y = curr val
# function returns a function
def returning_func():
def inner_func():
pass
return inner_func
# function takes a function as arg
def executing_func(some_func):
some_func()
executing_func(returning_func())
# decorators, externally adds extra functionality to func
from functools import wraps
def add_wrapping(func):
@wraps(func)
def wrapped_function():
return "Wrapped: {}".format(func())
return wrapped_function
@add_wrapping
def func_needs_decorator():
return "Needs dec"
print(func_needs_decorator())
GENERATORS (lazy eval)
==========
def generator_func(n):
for x in range(n)
yield x
for i in generator_func(5):
print(i)
next(generator_func(5))
s_iter = iter(string)
next(s_iter())
# Generator expression, lazy eval
g = (x for x in range(5))
next(g)
TYPE HINTS (static type checking)
==========
from typing import List, Dict
def annotated(x: int, y: List[int]) -> bool:
return x < y[0]
def annotated2(x: Dict[int, str]) -> str:
return x[0]
from typing import Optional, Any
# x is optional, can be None
# Any is compatible with every type
def annotated3(x: Optional[str] = None) -> Any:
pass
# forward reference (refer to class before defined)
class ToDo:
@classmethod
def list(cls) -> List['ToDo']:
return session.query(cls)
# type alias (Alias == Original, simplify complex type signatures)
# union = type can be from any of the provided type values
from typing import Union
GreetingType = Union[List[str], Dict[int, List[str]]]
def greeting(names: GreetingType) -> GreetingType:
pass
# type subtype (Derived subtype of Original)
# value of type Original cannot be used in places where a value of type Derived is expected
from typing import NewType
UserId = NewType('UserId', int)
CLASSES
==========
class ClassName(SuperClass):
class_variable = 0 # shared by all instances
__private_var = 'private' # only a convention
def __init__(self, var1, var2=1):
super().__init__()
self.var1 = var1 # unique to each instance
self.class_variable += var2
print(self.__class__)
def some_method(self):
return self.var1
# class of this object instance is implicitly passed as the first argument
# useful to create factory methods
@classmethod
def class_methold(cls, x):
return cls(x, 2)
# neither self nor the class is implicitly passed as the first argument
# useful to create utility methods
@staticmethod
def static_method(x):
print(x > 10)
raise NotImplementedError("abstract method")
# stingify object
def __str__(self):
return f"{self.var1} {self.__private_var}"
instance = ClassName(var1)
instance = ClassName.class_method(var1)
instance = instance.class_method(var1)
ClassName.static_method(var1)
instance.static_method(var1)
instance.var1
ClassName.class_variable
instance.class_variable
instance.some_method()
del instance
REGEX
==========
import re
pattern = r"(?P<var1>foo)"
m = re.search(pattern, text)
m.start() # starting index of match
m.group() # entire match
m.group(1) # first matching subgroup
m.group("var1") # access via group name
m.groups() # all matching subgroups in a tuple
re.sub(pattern, replacement, string)
COLLECTIONS
============
from collections import Counter
c = Counter(l)
Counter(String)
Counter(String.split())
c.most_common(n) # highest counts
c.most_common()[:-n-1:-1] # lowest counts
sum(c.values()) # total counts sum
d = dict(c) # dict of e:count
l = list(c) # list of e (unsorted)
l = list(c.items()) # list of (e, count) (unsorted)
s = set(c.items()) # set of (e, count) (unsorted)
from collections import defaultdict
d = defaultdict(lambda: None) # define default value
d['foo'] # returns None
from collections import Ordereddict
d = OrderedDict() # maintains order of insertion keys
from collections import namedtuple
T = namedtuple('TupleName', 'attr1 attr2')
t = T(attr1="foo", attr2="bar")
t.attr1
t[1]
from collections import deque
dq = deque()
dq.append(e)
dq.appendleft(e) # head
dq.pop()
dq.popleft() # head
dq[-1]
dq[0] # head
# heap / priority queue
import heapq
l = []
heapq.heapify(l) # convert list to heap
heapq.heappush(l, e)
heapq[0] # peek
heapq.heappop(l) # smallest ele
import timeit
timeit.timeit('function', number = iterations)
MULTIPROCESSING
===========
from multiprocessing import Process, Pool
# spawn 8 processes
for i in range(8):
p = Process(target=func, args=(var1, var2))
p.start()
p.join()
# pool with 8 processes
with Pool(8) as p:
data = p.map(func, range(1000))
print(data)
FILE IO
==========
file = open('filename.txt')
file.close()
file.read()
file.seek(0)
file.readlines() # list of lines
with open('file.txt', mode='a+') as file:
file.write('foo')
JSON
=====
import json
json.dumps(obj) # to json
json.loads(jsonStr) # from json
LOGGING
========
import logging
logging.basicConfig(level=logging.INFO)
logging.info("foo")
EXECUTE SHELL
=============
import subprocess
subprocess.run(['ls', '-l'], check=True) # Verify zero exit code
subprocess.run('ls -l', shell=True) # Execute as shell
out = subprocess.run(['ls'], capture_output=True, text=True).stdout # Grab output