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.

1523 lines
31 KiB

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