You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1479 lines
30 KiB

7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. <sup>[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md)
  4. or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet).
  5. </sup>
  6. ![Monty Python](web/image_888.jpeg)
  7. Main
  8. ----
  9. ```python
  10. if __name__ == '__main__':
  11. main()
  12. ```
  13. List
  14. ----
  15. ```python
  16. <list> = <list>[from_inclusive : to_exclusive : step_size]
  17. <list>.append(<el>)
  18. <list>.extend(<list>)
  19. <list> += [<el>]
  20. <list> += <list>
  21. ```
  22. ```python
  23. <list>.sort()
  24. <list>.reverse()
  25. <list> = sorted(<list>)
  26. <iter> = reversed(<list>)
  27. ```
  28. ```python
  29. sum_of_elements = sum(<list>)
  30. elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
  31. sorted_by_second = sorted(<list>, key=lambda el: el[1])
  32. sorted_by_both = sorted(<list>, key=lambda el: (el[1], el[0]))
  33. flattened_list = list(itertools.chain.from_iterable(<list>))
  34. list_of_chars = list(<str>)
  35. product_of_elems = functools.reduce(lambda out, x: out * x, <list>)
  36. no_duplicates = list(dict.fromkeys(<list>))
  37. ```
  38. ```python
  39. index = <list>.index(<el>) # Returns first index of item.
  40. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  41. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  42. <list>.remove(<el>) # Removes first occurrence of item.
  43. <list>.clear() # Removes all items.
  44. ```
  45. Dictionary
  46. ----------
  47. ```python
  48. <view> = <dict>.keys()
  49. <view> = <dict>.values()
  50. <view> = <dict>.items()
  51. ```
  52. ```python
  53. del <dict>[key] # Remove an existing key.
  54. value = <dict>.get(key, default) # Returns default if key does not exist.
  55. value = <dict>.setdefault(key, default) # Same, but also adds default to dict.
  56. <dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
  57. <dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
  58. ```
  59. ```python
  60. <dict>.update(<dict>)
  61. <dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
  62. <dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
  63. <dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
  64. {k: v for k, v in <dict>.items() if k in keys} # Filters a dict by keys.
  65. ```
  66. ### Counter
  67. ```python
  68. >>> from collections import Counter
  69. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  70. >>> Counter(colors)
  71. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  72. >>> <counter>.most_common()[0][0]
  73. 'blue'
  74. ```
  75. Set
  76. ---
  77. ```python
  78. <set> = set()
  79. <set>.add(<el>)
  80. <set>.update(<set>)
  81. <set>.clear()
  82. ```
  83. ```python
  84. <set> = <set>.union(<set>) # Or: <set> | <set>
  85. <set> = <set>.intersection(<set>) # Or: <set> & <set>
  86. <set> = <set>.difference(<set>) # Or: <set> - <set>
  87. <set> = <set>.symmetric_difference(<set>) # Or: <set> ^ <set>
  88. <bool> = <set>.issubset(<set>) # Or: <set> < <set>
  89. <bool> = <set>.issuperset(<set>) # Or: <set> > <set>
  90. ```
  91. ### Frozenset
  92. #### Is hashable and can be used as a key in dictionary.
  93. ```python
  94. <frozenset> = frozenset(<collection>)
  95. ```
  96. Range
  97. -----
  98. ```python
  99. range(to_exclusive)
  100. range(from_inclusive, to_exclusive)
  101. range(from_inclusive, to_exclusive, step_size)
  102. range(from_inclusive, to_exclusive, -step_size)
  103. ```
  104. ```python
  105. from_inclusive = <range>.start
  106. to_exclusive = <range>.stop
  107. ```
  108. Enumerate
  109. ---------
  110. ```python
  111. for i, <el> in enumerate(<collection> [, i_start]):
  112. ...
  113. ```
  114. Named Tuple
  115. -----------
  116. ```python
  117. >>> Point = collections.namedtuple('Point', 'x y')
  118. >>> p = Point(1, y=2)
  119. Point(x=1, y=2)
  120. >>> p[0]
  121. 1
  122. >>> p.x
  123. 1
  124. >>> getattr(p, 'y')
  125. 2
  126. >>> p._fields # Or: Point._fields
  127. ('x', 'y')
  128. ```
  129. Iterator
  130. --------
  131. #### Skips first element:
  132. ```python
  133. next(<iter>)
  134. for element in <iter>:
  135. ...
  136. ```
  137. #### Reads input until it reaches an empty line:
  138. ```python
  139. for line in iter(input, ''):
  140. ...
  141. ```
  142. #### Same, but prints a message every time:
  143. ```python
  144. from functools import partial
  145. for line in iter(partial(input, 'Please enter value: '), ''):
  146. ...
  147. ```
  148. Generator
  149. ---------
  150. **Convenient way to implement the iterator protocol.**
  151. ```python
  152. def step(start, step):
  153. while True:
  154. yield start
  155. start += step
  156. ```
  157. ```python
  158. >>> stepper = step(10, 2)
  159. >>> next(stepper), next(stepper), next(stepper)
  160. (10, 12, 14)
  161. ```
  162. Type
  163. ----
  164. ```python
  165. <type> = type(<el>) # <class 'int'> / <class 'str'> / ...
  166. ```
  167. ```python
  168. from numbers import Number, Integral, Real, Rational, Complex
  169. is_number = isinstance(<el>, Number)
  170. is_function = callable(<el>)
  171. ```
  172. String
  173. ------
  174. ```python
  175. <str> = <str>.strip() # Strips all whitespace characters.
  176. <str> = <str>.strip('<chars>') # Strips all passed characters.
  177. ```
  178. ```python
  179. <list> = <str>.split() # Splits on any whitespace character.
  180. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' at most 'maxsplit' times.
  181. <str> = <str>.join(<list>) # Joins elements using string as separator.
  182. ```
  183. ```python
  184. <str> = <str>.replace(old_str, new_str)
  185. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  186. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  187. <int> = <str>.index(<sub_str>) # Returns first index of a substring.
  188. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  189. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  190. ```
  191. ### Char
  192. ```python
  193. <str> = chr(<int>) # Converts int to unicode char.
  194. <int> = ord(<str>) # Converts unicode char to int.
  195. ```
  196. ```python
  197. >>> ord('0'), ord('9')
  198. (48, 57)
  199. >>> ord('A'), ord('Z')
  200. (65, 90)
  201. >>> ord('a'), ord('z')
  202. (97, 122)
  203. ```
  204. ### Print
  205. ```python
  206. print(<el_1> [, <el_2>, end='', sep='', file=<file>]) # Use 'file=sys.stderr' for errors.
  207. ```
  208. ```python
  209. >>> from pprint import pprint
  210. >>> pprint(locals())
  211. {'__doc__': None,
  212. '__name__': '__main__',
  213. '__package__': None, ...}
  214. ```
  215. Regex
  216. -----
  217. ```python
  218. import re
  219. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  220. <list> = re.findall(<regex>, text)
  221. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  222. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  223. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  224. <Match_iter> = re.finditer(<regex>, text) # Searches for all occurrences of pattern.
  225. ```
  226. * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.**
  227. * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.**
  228. * **Use `r'\1'` or `'\\\\1'` for backreference.**
  229. * **Use `'?'` to make operators non-greedy.**
  230. ### Match Object
  231. ```python
  232. <str> = <Match>.group() # Whole match.
  233. <str> = <Match>.group(1) # Part in first bracket.
  234. <int> = <Match>.start() # Start index of a match.
  235. <int> = <Match>.end() # Exclusive end index of a match.
  236. ```
  237. ### Special Sequences
  238. **Use capital letter for negation.**
  239. ```python
  240. '\d' == '[0-9]' # Digit
  241. '\s' == '[ \t\n\r\f\v]' # Whitespace
  242. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  243. ```
  244. Format
  245. ------
  246. ```python
  247. <str> = f'{<el_1>}, {<el_2>}'
  248. <str> = '{}, {}'.format(<el_1>, <el_2>)
  249. ```
  250. ```python
  251. >>> Person = namedtuple('Person', 'name height')
  252. >>> person = Person('Jean-Luc', 187)
  253. >>> f'{person.height:10}'
  254. ' 187'
  255. >>> '{p.height:10}'.format(p=person)
  256. ' 187'
  257. ```
  258. ### General Options
  259. ```python
  260. {<el>:<10} # '<el> '
  261. {<el>:>10} # ' <el>'
  262. {<el>:^10} # ' <el> '
  263. {<el>:->10} # '------<el>'
  264. {<el>:>0} # '<el>'
  265. ```
  266. ### String Options
  267. **"!r" uses object's repr() method, instead of format(), to get a string:**
  268. ```python
  269. {'abcde'!r} # "'abcde'"
  270. ```
  271. ```python
  272. {'abcde':.3} # 'abc'
  273. {'abcde':10.3} # 'abc '
  274. ```
  275. ### Number Options
  276. ```python
  277. {1.23456:.3f} # '1.235'
  278. {1.23456:10.3f} # ' 1.235'
  279. ```
  280. ```python
  281. {123456:10,} # ' 123,456'
  282. {123456:10_} # ' 123_456'
  283. {123456:+10} # ' +123456'
  284. {-123456:=10} # '- 123456'
  285. {123456: } # ' 123456'
  286. {-123456: } # '-123456'
  287. ```
  288. ```python
  289. {65:c} # 'A'
  290. {3:08b} # '00000011' -> Binary with leading zeros.
  291. {3:0<8b} # '11000000' -> Binary with trailing zeros.
  292. ```
  293. #### Float presentation types:
  294. * `'f'` - Fixed point: `.<precision>f`
  295. * `'%'` - Percent: `.<precision>%`
  296. * `'e'` - Exponent
  297. #### Integer presentation types:
  298. * `'c'` - Character
  299. * `'b'` - Binary
  300. * `'x'` - Hex
  301. * `'X'` - HEX
  302. Numbers
  303. -------
  304. ### Basic Functions
  305. ```python
  306. pow(x, y) # Or: x ** y
  307. abs(<num>)
  308. round(<num> [, ndigits])
  309. ```
  310. ### Constants
  311. ```python
  312. from math import e, pi
  313. ```
  314. ### Trigonometry
  315. ```python
  316. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  317. ```
  318. ### Logarithm
  319. ```python
  320. from math import log, log10, log2
  321. log(x [, base]) # Base e, if not specified.
  322. log10(x) # Base 10.
  323. log2(x) # Base 2.
  324. ```
  325. ### Infinity, nan
  326. ```python
  327. from math import inf, nan, isinf, isnan
  328. ```
  329. #### Or:
  330. ```python
  331. float('inf'), float('nan')
  332. ```
  333. ### Random
  334. ```python
  335. from random import random, randint, choice, shuffle
  336. <float> = random()
  337. <int> = randint(from_inclusive, to_inclusive)
  338. <el> = choice(<list>)
  339. shuffle(<list>)
  340. ```
  341. Datetime
  342. --------
  343. ```python
  344. from datetime import datetime, strptime
  345. now = datetime.now()
  346. now.month # 3
  347. now.strftime('%Y%m%d') # '20180315'
  348. now.strftime('%Y%m%d%H%M%S') # '20180315002834'
  349. <datetime> = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
  350. ```
  351. Arguments
  352. ---------
  353. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.**
  354. ```python
  355. args = (1, 2)
  356. kwargs = {'x': 3, 'y': 4, 'z': 5}
  357. func(*args, **kwargs)
  358. ```
  359. #### Is the same as:
  360. ```python
  361. func(1, 2, x=3, y=4, z=5)
  362. ```
  363. #### Splat operator can also be used in function declarations:
  364. ```python
  365. def add(*a):
  366. return sum(a)
  367. ```
  368. ```python
  369. >>> add(1, 2, 3)
  370. 6
  371. ```
  372. #### And in few other places:
  373. ```python
  374. >>> a = (1, 2, 3)
  375. >>> [*a]
  376. [1, 2, 3]
  377. ```
  378. ```python
  379. >>> head, *body, tail = [1, 2, 3, 4]
  380. >>> body
  381. [2, 3]
  382. ```
  383. Inline
  384. ------
  385. ### Lambda
  386. ```python
  387. lambda: <return_value>
  388. lambda <argument_1>, <argument_2>: <return_value>
  389. ```
  390. ### Comprehension
  391. ```python
  392. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  393. <set> = {i for i in range(10) if i > 5} # {6, 7, ..., 9}
  394. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  395. <iter> = (x+5 for x in range(10)) # (5, 6, ..., 14)
  396. ```
  397. ```python
  398. out = [i+j for i in range(10) for j in range(10)]
  399. ```
  400. #### Is the same as:
  401. ```python
  402. out = []
  403. for i in range(10):
  404. for j in range(10):
  405. out.append(i+j)
  406. ```
  407. ### Map, Filter, Reduce
  408. ```python
  409. from functools import reduce
  410. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  411. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, ..., 9)
  412. <any_type> = reduce(lambda out, x: out + x, range(10)) # 45
  413. ```
  414. ### Any, All
  415. ```python
  416. <bool> = any(el[1] for el in <collection>)
  417. ```
  418. ### If - Else
  419. ```python
  420. <expression_if_true> if <condition> else <expression_if_false>
  421. ```
  422. ```python
  423. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  424. ['zero', 1, 'zero', 3]
  425. ```
  426. ### Namedtuple, Enum, Class
  427. ```python
  428. from collections import namedtuple
  429. Point = namedtuple('Point', 'x y')
  430. from enum import Enum
  431. Direction = Enum('Direction', 'n e s w')
  432. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  433. # Warning: Objects will share the objects that are initialized in the dictionary!
  434. Creature = type('Creature', (), {'position': Point(0, 0), 'direction': Direction.n})
  435. creature = Creature()
  436. ```
  437. Closure
  438. -------
  439. ```python
  440. def get_multiplier(a):
  441. def out(b):
  442. return a * b
  443. return out
  444. ```
  445. ```python
  446. >>> multiply_by_3 = get_multiplier(3)
  447. >>> multiply_by_3(10)
  448. 30
  449. ```
  450. #### Or:
  451. ```python
  452. from functools import partial
  453. <function> = partial(<function>, <argument_1> [, <argument_2>, ...])
  454. ```
  455. ```python
  456. >>> multiply_by_3 = partial(operator.mul, 3)
  457. >>> multiply_by_3(10)
  458. 30
  459. ```
  460. Decorator
  461. ---------
  462. ```python
  463. @closure_name
  464. def function_that_gets_passed_to_closure():
  465. ...
  466. ```
  467. #### Debugger example:
  468. ```python
  469. from functools import wraps
  470. def debug(func):
  471. @wraps(func) # Needed for metadata copying (func name, ...).
  472. def out(*args, **kwargs):
  473. print(func.__name__)
  474. return func(*args, **kwargs)
  475. return out
  476. @debug
  477. def add(x, y):
  478. return x + y
  479. ```
  480. Class
  481. -----
  482. ```python
  483. class <name>:
  484. def __init__(self, a):
  485. self.a = a
  486. def __str__(self):
  487. return str(self.a)
  488. def __repr__(self):
  489. return str({'a': self.a}) # Or: return f'{self.__dict__}'
  490. @classmethod
  491. def get_class_name(cls):
  492. return cls.__name__
  493. ```
  494. ### Constructor Overloading
  495. ```python
  496. class <name>:
  497. def __init__(self, a=None):
  498. self.a = a
  499. ```
  500. ### Inheritance
  501. ```python
  502. class Person:
  503. def __init__(self, name, age):
  504. self.name = name
  505. self.age = age
  506. class Employee(Person):
  507. def __init__(self, name, age, staff_num):
  508. super().__init__(name, age)
  509. self.staff_num = staff_num
  510. ```
  511. ### Copy
  512. ```python
  513. from copy import copy, deepcopy
  514. <object> = copy(<object>)
  515. <object> = deepcopy(<object>)
  516. ```
  517. Enum
  518. ----
  519. ```python
  520. from enum import Enum, auto
  521. class <enum_name>(Enum):
  522. <member_name_1> = <value_1>
  523. <member_name_2> = <value_2_a>, <value_2_b>
  524. <member_name_3> = auto() # Can be used for automatic indexing.
  525. ...
  526. @classmethod
  527. def get_names(cls):
  528. return [a.name for a in cls.__members__.values()]
  529. ```
  530. ```python
  531. <member> = <enum>.<member_name>
  532. <member> = <enum>['<member_name>']
  533. <member> = <enum>(<value>)
  534. <name> = <member>.name
  535. <value> = <member>.value
  536. ```
  537. ```python
  538. list_of_members = list(<enum>)
  539. member_names = [a.name for a in <enum>]
  540. member_values = [a.value for a in <enum>]
  541. random_member = random.choice(list(<enum>))
  542. ```
  543. ### Inline
  544. ```python
  545. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  546. Cutlery = Enum('Cutlery', 'knife fork spoon')
  547. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  548. # Functions can not be values, so they must be enclosed in tuple:
  549. LogicOp = Enum('LogicOp', {'AND': (lambda l, r: l and r, ),
  550. 'OR' : (lambda l, r: l or r, )})
  551. # But 'list(<enum>)' will only work if there is another value in the tuple:
  552. LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r),
  553. 'OR' : (auto(), lambda l, r: l or r)})
  554. ```
  555. System
  556. ------
  557. ### Arguments
  558. ```python
  559. import sys
  560. script_name = sys.argv[0]
  561. arguments = sys.argv[1:]
  562. ```
  563. ### Read File
  564. ```python
  565. def read_file(filename):
  566. with open(filename, encoding='utf-8') as file:
  567. return file.readlines()
  568. ```
  569. ### Write to File
  570. ```python
  571. def write_to_file(filename, text):
  572. with open(filename, 'w', encoding='utf-8') as file:
  573. file.write(text)
  574. ```
  575. ### Path
  576. ```python
  577. from os import path, listdir
  578. <bool> = path.exists(<path>)
  579. <bool> = path.isfile(<path>)
  580. <bool> = path.isdir(<path>)
  581. <list> = listdir(<path>)
  582. ```
  583. ```python
  584. >>> from glob import glob
  585. >>> glob('../*.gif')
  586. ['1.gif', 'card.gif']
  587. ```
  588. ### Execute Command
  589. ```python
  590. import os
  591. <str> = os.popen(<command>).read()
  592. ```
  593. #### Or:
  594. ```python
  595. >>> import subprocess
  596. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  597. >>> a.stdout
  598. b'.\n..\nfile1.txt\nfile2.txt\n'
  599. >>> a.returncode
  600. 0
  601. ```
  602. ### Input
  603. ```python
  604. filename = input('Enter a file name: ')
  605. ```
  606. #### Prints lines until EOF:
  607. ```python
  608. while True:
  609. try:
  610. print(input())
  611. except EOFError:
  612. break
  613. ```
  614. ### Recursion Limit
  615. ```python
  616. >>> sys.getrecursionlimit()
  617. 1000
  618. >>> sys.setrecursionlimit(10000)
  619. ```
  620. JSON
  621. ----
  622. ```python
  623. import json
  624. ```
  625. ### Serialization
  626. ```python
  627. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  628. <dict> = json.loads(<str>)
  629. ```
  630. #### To preserve order:
  631. ```python
  632. from collections import OrderedDict
  633. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  634. ```
  635. ### Read File
  636. ```python
  637. def read_json_file(filename):
  638. with open(filename, encoding='utf-8') as file:
  639. return json.load(file)
  640. ```
  641. ### Write to File
  642. ```python
  643. def write_to_json_file(filename, an_object):
  644. with open(filename, 'w', encoding='utf-8') as file:
  645. json.dump(an_object, file, ensure_ascii=False, indent=2)
  646. ```
  647. SQLite
  648. ------
  649. ```python
  650. import sqlite3
  651. db = sqlite3.connect(<filename>)
  652. ```
  653. ### Read
  654. ```python
  655. cursor = db.execute(<query>)
  656. if cursor:
  657. <tuple> = cursor.fetchone() # First row.
  658. <list> = cursor.fetchall() # Remaining rows.
  659. db.close()
  660. ```
  661. ### Write
  662. ```python
  663. db.execute(<query>)
  664. db.commit()
  665. ```
  666. Pickle
  667. ------
  668. ```python
  669. >>> import pickle
  670. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  671. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  672. >>> pickle.load(open('data.p', 'rb'))
  673. {'lion': 'yellow', 'kitty': 'red'}
  674. ```
  675. Exceptions
  676. ----------
  677. ```python
  678. while True:
  679. try:
  680. x = int(input('Please enter a number: '))
  681. except ValueError:
  682. print('Oops! That was no valid number. Try again...')
  683. else:
  684. print('Thank you.')
  685. break
  686. ```
  687. #### Raising exception:
  688. ```python
  689. raise ValueError('A very specific message!')
  690. ```
  691. ### Finally
  692. ```python
  693. >>> try:
  694. ... raise KeyboardInterrupt
  695. ... finally:
  696. ... print('Goodbye, world!')
  697. Goodbye, world!
  698. Traceback (most recent call last):
  699. File "<stdin>", line 2, in <module>
  700. KeyboardInterrupt
  701. ```
  702. Bytes
  703. -----
  704. **Bytes objects are immutable sequences of single bytes.**
  705. ### Encode
  706. ```python
  707. <Bytes> = b'<str>'
  708. <Bytes> = <str>.encode(encoding='utf-8')
  709. <Bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
  710. <Bytes> = bytes.fromhex(<hex>)
  711. ```
  712. ### Decode
  713. ```python
  714. <str> = <Bytes>.decode('utf-8')
  715. <int> = int.from_bytes(<Bytes>, byteorder='big|little', signed=False)
  716. <hex> = <Bytes>.hex()
  717. ```
  718. ### Read Bytes from File
  719. ```python
  720. def read_bytes(filename):
  721. with open(filename, 'rb') as file:
  722. return file.read()
  723. ```
  724. ### Write Bytes to File
  725. ```python
  726. def write_bytes(filename, bytes):
  727. with open(filename, 'wb') as file:
  728. file.write(bytes)
  729. ```
  730. ```python
  731. <Bytes> = b''.join(<list_of_Bytes>)
  732. ```
  733. Struct
  734. ------
  735. **This module performs conversions between Python values and C struct represented as Python Bytes object.**
  736. ```python
  737. from struct import pack, unpack
  738. <Bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  739. <tuple> = unpack('<format>', <Bytes>)
  740. ```
  741. ### Example
  742. ```python
  743. >>> pack('hhl', 1, 2, 3)
  744. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  745. >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  746. (1, 2, 3)
  747. >>> calcsize('hhl')
  748. 8
  749. ```
  750. ### Format
  751. **Use capital leters for unsigned type.**
  752. * `'x'` - pad byte
  753. * `'c'` - char
  754. * `'h'` - short
  755. * `'i'` - int
  756. * `'l'` - long
  757. * `'q'` - long long
  758. * `'f'` - float
  759. * `'d'` - double
  760. Hashlib
  761. -------
  762. ```python
  763. >>> hashlib.md5(<str>.encode()).hexdigest()
  764. '33d0eba106da4d3ebca17fcd3f4c3d77'
  765. ```
  766. Threading
  767. ---------
  768. ```python
  769. from threading import Thread, RLock
  770. ```
  771. ### Thread
  772. ```python
  773. thread = Thread(target=<function>, args=(<first_arg>, ))
  774. thread.start()
  775. ...
  776. thread.join()
  777. ```
  778. ### Lock
  779. ```python
  780. lock = Rlock()
  781. lock.acquire()
  782. ...
  783. lock.release()
  784. ```
  785. Itertools
  786. ---------
  787. **Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function.**
  788. ```python
  789. from itertools import *
  790. ```
  791. ### Combinatoric iterators
  792. ```python
  793. >>> combinations('abc', 2)
  794. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  795. >>> combinations_with_replacement('abc', 2)
  796. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  797. ('b', 'b'), ('b', 'c'),
  798. ('c', 'c')]
  799. >>> permutations('abc', 2)
  800. [('a', 'b'), ('a', 'c'),
  801. ('b', 'a'), ('b', 'c'),
  802. ('c', 'a'), ('c', 'b')]
  803. >>> product('ab', [1, 2])
  804. [('a', 1), ('a', 2),
  805. ('b', 1), ('b', 2)]
  806. >>> product([0, 1], repeat=3)
  807. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  808. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  809. ```
  810. ### Infinite iterators
  811. ```python
  812. >>> i = count(5, 2)
  813. >>> next(i), next(i), next(i)
  814. (5, 7, 9)
  815. >>> a = cycle('abc')
  816. >>> [next(a) for _ in range(10)]
  817. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  818. >>> repeat(10, 3)
  819. [10, 10, 10]
  820. ```
  821. ### Iterators
  822. ```python
  823. >>> chain([1, 2], range(3, 5))
  824. [1, 2, 3, 4]
  825. >>> compress('abc', [True, 0, 1])
  826. ['a', 'c']
  827. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  828. [2, 3]
  829. >>> people = [{'id': 1, 'name': 'bob'},
  830. {'id': 2, 'name': 'bob'},
  831. {'id': 3, 'name': 'peter'}]
  832. >>> {name: list(ppp) for name, ppp in groupby(people, key=lambda p: p['name'])}
  833. {'bob': [{'id': 1, 'name': 'bob'},
  834. {'id': 2, 'name': 'bob'}],
  835. 'peter': [{'id': 3, 'name': 'peter'}]}
  836. ```
  837. Introspection and Metaprograming
  838. --------------------------------
  839. **Inspecting code at runtime and code that generates code. You can:**
  840. * **Look at the attributes**
  841. * **Set new attributes**
  842. * **Create functions dynamically**
  843. * **Traverse the parent classes**
  844. * **Change values in the class**
  845. ### Variables
  846. ```python
  847. <list> = dir() # In-scope variables.
  848. <dict> = locals() # Local variables.
  849. <dict> = globals() # Global variables.
  850. ```
  851. ### Attributes
  852. ```python
  853. >>> class Z:
  854. ... def __init__(self):
  855. ... self.a = 'abcde'
  856. ... self.b = 12345
  857. >>> z = Z()
  858. ```
  859. ```python
  860. >>> vars(z)
  861. {'a': 'abcde', 'b': 12345}
  862. >>> getattr(z, 'a')
  863. 'abcde'
  864. >>> hasattr(z, 'c')
  865. False
  866. >>> setattr(z, 'c', 10)
  867. ```
  868. ### Parameters
  869. #### Getting the number of parameters of a function:
  870. ```python
  871. from inspect import signature
  872. sig = signature(<function>)
  873. no_of_params = len(sig.parameters)
  874. ```
  875. ### Type
  876. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!):**
  877. ```python
  878. type(<class_name>, <parents_tuple>, <attributes_dict>)
  879. ```
  880. ```python
  881. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  882. >>> z = Z()
  883. ```
  884. ### Meta Class
  885. #### Class that creates class.
  886. ```python
  887. def my_meta_class(name, parents, attrs):
  888. ...
  889. return type(name, parents, attrs)
  890. ```
  891. #### Or:
  892. ```python
  893. class MyMetaClass(type):
  894. def __new__(klass, name, parents, attrs):
  895. ...
  896. return type.__new__(klass, name, parents, attrs)
  897. ```
  898. ### Metaclass Attribute
  899. **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type:**
  900. ```python
  901. class BlaBla:
  902. __metaclass__ = Bla
  903. ```
  904. Operator
  905. --------
  906. ```python
  907. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  908. eq, ne, lt, le, gt, ge, \
  909. not_, and_, or_, \
  910. itemgetter
  911. ```
  912. ```python
  913. import operator as op
  914. product_of_elems = functools.reduce(op.mul, <list>)
  915. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  916. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  917. LogicOp = Enum('LogicOp', {'AND': (op.and_, ),
  918. 'OR' : (op.or_, )})
  919. ```
  920. Eval
  921. ----
  922. ### Basic
  923. ```python
  924. >>> from ast import literal_eval
  925. >>> literal_eval('1 + 2')
  926. 3
  927. >>> literal_eval('[1, 2, 3]')
  928. [1, 2, 3]
  929. ```
  930. ### Using Abstract Syntax Trees
  931. ```python
  932. import ast
  933. from ast import Num, BinOp, UnaryOp
  934. import operator as op
  935. legal_operators = {ast.Add: op.add,
  936. ast.Sub: op.sub,
  937. ast.Mult: op.mul,
  938. ast.Div: op.truediv,
  939. ast.Pow: op.pow,
  940. ast.BitXor: op.xor,
  941. ast.USub: op.neg}
  942. def evaluate(expression):
  943. root = ast.parse(expression, mode='eval')
  944. return eval_node(root.body)
  945. def eval_node(node):
  946. node_type = type(node)
  947. if node_type == Num:
  948. return node.n
  949. if node_type not in [BinOp, UnaryOp]:
  950. raise TypeError(node)
  951. operator_type = type(node.op)
  952. if operator_type not in legal_operators:
  953. raise TypeError(f'Illegal operator {node.op}')
  954. operator = legal_operators[operator_type]
  955. if node_type == BinOp:
  956. left, right = eval_node(node.left), eval_node(node.right)
  957. return operator(left, right)
  958. elif node_type == UnaryOp:
  959. operand = eval_node(node.operand)
  960. return operator(operand)
  961. ```
  962. ```python
  963. >>> evaluate('2^6')
  964. 4
  965. >>> evaluate('2**6')
  966. 64
  967. >>> evaluate('1 + 2*3**(4^5) / (6 + -7)')
  968. -5.0
  969. ```
  970. Coroutine
  971. ---------
  972. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  973. * **Coroutines provide more powerful data routing possibilities than iterators.**
  974. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  975. ### Helper Decorator
  976. * **All coroutines must be "primed" by first calling next().**
  977. * **Remembering to call next() is easy to forget.**
  978. * **Solved by wrapping coroutines with a decorator:**
  979. ```python
  980. def coroutine(func):
  981. def out(*args, **kwargs):
  982. cr = func(*args, **kwargs)
  983. next(cr)
  984. return cr
  985. return out
  986. ```
  987. ### Pipeline Example
  988. ```python
  989. def reader(target):
  990. for i in range(10):
  991. target.send(i)
  992. target.close()
  993. @coroutine
  994. def adder(target):
  995. while True:
  996. item = (yield)
  997. target.send(item + 100)
  998. @coroutine
  999. def printer():
  1000. while True:
  1001. item = (yield)
  1002. print(item)
  1003. reader(adder(printer()))
  1004. ```
  1005. <br><br>
  1006. Libraries
  1007. =========
  1008. Plot
  1009. ----
  1010. ```python
  1011. # $ pip3 install matplotlib
  1012. from matplotlib import pyplot
  1013. pyplot.plot(<data_1> [, <data_2>, ...])
  1014. pyplot.show()
  1015. pyplot.savefig(<filename>, transparent=True)
  1016. ```
  1017. Progress Bar
  1018. ------------
  1019. ```python
  1020. # $ pip3 install tqdm
  1021. from tqdm import tqdm
  1022. from time import sleep
  1023. for i in tqdm(range(100)):
  1024. sleep(0.02)
  1025. for i in tqdm([1, 2, 3]):
  1026. sleep(0.2)
  1027. ```
  1028. Table
  1029. -----
  1030. #### Prints CSV file as ASCII table:
  1031. ```python
  1032. # $ pip3 install tabulate
  1033. from csv import reader
  1034. from tabulate import tabulate
  1035. with open(<filename>, newline='') as csv_file:
  1036. reader = reader(csv_file, delimiter=';')
  1037. headers = [a.title() for a in next(reader)]
  1038. print(tabulate(reader, headers))
  1039. ```
  1040. Curses
  1041. ------
  1042. ```python
  1043. # $ pip3 install curses
  1044. from curses import wrapper
  1045. def main():
  1046. wrapper(draw)
  1047. def draw(screen):
  1048. screen.clear()
  1049. screen.addstr(0, 0, 'Press ESC to quit.')
  1050. while screen.getch() != 27:
  1051. pass
  1052. def get_border(screen):
  1053. from collections import namedtuple
  1054. P = namedtuple('P', 'x y')
  1055. height, width = screen.getmaxyx()
  1056. return P(width - 1, height - 1)
  1057. ```
  1058. Image
  1059. -----
  1060. #### Creates PNG image of greyscale gradient:
  1061. ```python
  1062. # $ pip3 install pillow
  1063. from PIL import Image
  1064. width, height = 100, 100
  1065. img = Image.new('L', (width, height), 'white')
  1066. img.putdata([255*a/(width*height) for a in range(width*height)])
  1067. img.save('out.png')
  1068. ```
  1069. ### Modes
  1070. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1071. * `'L'` - 8-bit pixels, greyscale.
  1072. * `'RGB'` - 3x8-bit pixels, true color.
  1073. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1074. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1075. Audio
  1076. -----
  1077. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1078. ```python
  1079. import wave, struct
  1080. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1081. wf = wave.open(<filename>, 'wb')
  1082. wf.setnchannels(1)
  1083. wf.setsampwidth(4)
  1084. wf.setframerate(44100)
  1085. wf.writeframes(b''.join(frames))
  1086. wf.close()
  1087. ```
  1088. Url
  1089. ---
  1090. ```python
  1091. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1092. ```
  1093. ### Encode
  1094. ```python
  1095. >>> quote("Can't be in URL!")
  1096. 'Can%27t%20be%20in%20URL%21'
  1097. >>> quote_plus("Can't be in URL!")
  1098. 'Can%27t+be+in+URL%21'
  1099. ```
  1100. ### Decode
  1101. ```python
  1102. >>> unquote('Can%27t+be+in+URL%21')
  1103. "Can't+be+in+URL!"'
  1104. >>> unquote_plus('Can%27t+be+in+URL%21')
  1105. "Can't be in URL!"
  1106. ```
  1107. Scraping
  1108. --------
  1109. ```python
  1110. # $ pip3 install requests beautifulsoup4
  1111. >>> import requests
  1112. >>> from bs4 import BeautifulSoup
  1113. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1114. >>> page = requests.get(url)
  1115. >>> document = BeautifulSoup(page.text, 'html.parser')
  1116. >>> table = document.find('table', class_='infobox vevent')
  1117. >>> rows = table.find_all('tr')
  1118. >>> website = rows[11].find('a')['href']
  1119. 'https://www.python.org/'
  1120. >>> latest_v = rows[6].find('div').text.split()[0]
  1121. '3.7.2'
  1122. ```
  1123. Web
  1124. ---
  1125. ```python
  1126. # $ pip3 install bottle
  1127. import bottle
  1128. from urllib.parse import unquote
  1129. ```
  1130. ### Run
  1131. ```python
  1132. bottle.run(host='localhost', port=8080)
  1133. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1134. ```
  1135. ### Static Request
  1136. ```python
  1137. @route('/img/<image>')
  1138. def send_image(image):
  1139. return static_file(image, 'images/', mimetype='image/png')
  1140. ```
  1141. ### Dynamic Request
  1142. ```python
  1143. @route('/<sport>')
  1144. def send_page(sport):
  1145. sport = unquote(sport).lower()
  1146. page = read_file(sport)
  1147. return template(page)
  1148. ```
  1149. ### REST Request
  1150. ```python
  1151. @post('/odds/<sport>')
  1152. def odds_handler(sport):
  1153. team = bottle.request.forms.get('team')
  1154. team = unquote(team).lower()
  1155. db = sqlite3.connect(<db_path>)
  1156. home_odds, away_odds = get_odds(db, sport, team)
  1157. db.close()
  1158. response.headers['Content-Type'] = 'application/json'
  1159. response.headers['Cache-Control'] = 'no-cache'
  1160. return json.dumps([home_odds, away_odds])
  1161. ```
  1162. Profile
  1163. -------
  1164. ### Basic
  1165. ```python
  1166. from time import time
  1167. start_time = time()
  1168. ...
  1169. duration = time() - start_time
  1170. ```
  1171. ### Timing a Snippet
  1172. ```python
  1173. from timeit import timeit
  1174. timeit('"-".join(str(a) for a in range(100))',
  1175. number=10000, globals=globals())
  1176. ```
  1177. ### Line Profiler
  1178. ```python
  1179. # $ pip3 install line_profiler
  1180. @profile
  1181. def main():
  1182. a = [*range(10000)]
  1183. b = {*range(10000)}
  1184. main()
  1185. ```
  1186. ```
  1187. $ kernprof -lv test.py
  1188. Line # Hits Time Per Hit % Time Line Contents
  1189. ==============================================================
  1190. 1 @profile
  1191. 2 def main():
  1192. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1193. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1194. ```
  1195. ### Call Graph
  1196. #### Generates a PNG image of call graph with highlighted bottlenecks.
  1197. ```python
  1198. # $ pip3 install pycallgraph
  1199. from pycallgraph import output, PyCallGraph
  1200. from datetime import datetime
  1201. graph = output.GraphvizOutput()
  1202. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1203. graph.output_file = f'profile-{time_str}.png'
  1204. with PyCallGraph(output=graph):
  1205. <code_to_be_profiled>
  1206. ```
  1207. Basic Script Template
  1208. ---------------------
  1209. ```python
  1210. #!/usr/bin/env python3
  1211. #
  1212. # Usage: .py
  1213. #
  1214. from collections import namedtuple
  1215. from enum import Enum
  1216. import re
  1217. import sys
  1218. def main():
  1219. pass
  1220. ###
  1221. ## UTIL
  1222. #
  1223. def read_file(filename):
  1224. with open(filename, encoding='utf-8') as file:
  1225. return file.readlines()
  1226. if __name__ == '__main__':
  1227. main()
  1228. ```