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.

1839 lines
39 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
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
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
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
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
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
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
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
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
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
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
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
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
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
7 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
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
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
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
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
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
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
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
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
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
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
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 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
6 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
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
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
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
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
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
  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(<collection>)
  19. <list> += [<el>]
  20. <list> += <collection>
  21. ```
  22. ```python
  23. <list>.sort()
  24. <list>.reverse()
  25. <list> = sorted(<collection>)
  26. <iter> = reversed(<list>)
  27. ```
  28. ```python
  29. sum_of_elements = sum(<collection>)
  30. elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
  31. sorted_by_second = sorted(<collection>, key=lambda el: el[1])
  32. sorted_by_both = sorted(<collection>, 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, <collection>)
  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>) # Or: dict_a = {**dict_a, **dict_b}.
  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. ```
  64. ```python
  65. value = <dict>.pop(key) # Removes item from dictionary.
  66. {k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
  67. ```
  68. ### Counter
  69. ```python
  70. >>> from collections import Counter
  71. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  72. >>> counter = Counter(colors)
  73. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  74. >>> counter.most_common()[0][0]
  75. 'blue'
  76. ```
  77. Set
  78. ---
  79. ```python
  80. <set> = set()
  81. <set>.add(<el>)
  82. <set>.update(<collection>)
  83. <set> |= {<el>}
  84. <set> |= <set>
  85. ```
  86. ```python
  87. <set> = <set>.union(<coll.>) # Or: <set> | <set>
  88. <set> = <set>.intersection(<coll.>) # Or: <set> & <set>
  89. <set> = <set>.difference(<coll.>) # Or: <set> - <set>
  90. <set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
  91. <bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
  92. <bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
  93. ```
  94. ```python
  95. <set>.remove(<el>) # Throws error.
  96. <set>.discard(<el>) # Doesn't throw error.
  97. ```
  98. ### Frozenset
  99. #### Is hashable and can be used as a key in dictionary.
  100. ```python
  101. <frozenset> = frozenset(<collection>)
  102. ```
  103. Range
  104. -----
  105. ```python
  106. range(to_exclusive)
  107. range(from_inclusive, to_exclusive)
  108. range(from_inclusive, to_exclusive, step_size)
  109. range(from_inclusive, to_exclusive, -step_size)
  110. ```
  111. ```python
  112. from_inclusive = <range>.start
  113. to_exclusive = <range>.stop
  114. ```
  115. Enumerate
  116. ---------
  117. ```python
  118. for i, el in enumerate(<collection> [, i_start]):
  119. ...
  120. ```
  121. Named Tuple
  122. -----------
  123. ```python
  124. >>> Point = collections.namedtuple('Point', 'x y')
  125. >>> p = Point(1, y=2)
  126. Point(x=1, y=2)
  127. >>> p[0]
  128. 1
  129. >>> p.x
  130. 1
  131. >>> getattr(p, 'y')
  132. 2
  133. >>> p._fields # Or: Point._fields
  134. ('x', 'y')
  135. ```
  136. Iterator
  137. --------
  138. ```python
  139. <iter> = iter(<collection>)
  140. <iter> = iter(<function>, to_exclusive)
  141. ```
  142. #### Skips first element:
  143. ```python
  144. next(<iter>)
  145. for element in <iter>:
  146. ...
  147. ```
  148. #### Reads input until it reaches an empty line:
  149. ```python
  150. for line in iter(input, ''):
  151. ...
  152. ```
  153. #### Same, but prints a message every time:
  154. ```python
  155. from functools import partial
  156. for line in iter(partial(input, 'Please enter value: '), ''):
  157. ...
  158. ```
  159. Generator
  160. ---------
  161. **Convenient way to implement the iterator protocol.**
  162. ```python
  163. def step(start, step_size):
  164. while True:
  165. yield start
  166. start += step_size
  167. ```
  168. ```python
  169. >>> stepper = step(10, 2)
  170. >>> next(stepper), next(stepper), next(stepper)
  171. (10, 12, 14)
  172. ```
  173. Type
  174. ----
  175. ```python
  176. <type> = type(<el>) # <class 'int'> / <class 'str'> / ...
  177. ```
  178. ```python
  179. from numbers import Number, Integral, Real, Rational, Complex
  180. <bool> = isinstance(<el>, Number)
  181. ```
  182. ```python
  183. <bool> = callable(<el>)
  184. ```
  185. String
  186. ------
  187. ```python
  188. <str> = <str>.strip() # Strips all whitespace characters.
  189. <str> = <str>.strip('<chars>') # Strips all passed characters.
  190. ```
  191. ```python
  192. <list> = <str>.split() # Splits on any whitespace character.
  193. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
  194. <str> = <str>.join(<list>) # Joins elements using string as separator.
  195. ```
  196. ```python
  197. <str> = <str>.replace(old_str, new_str)
  198. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  199. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  200. <int> = <str>.index(<sub_str>) # Returns first index of a substring.
  201. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  202. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  203. ```
  204. ### Char
  205. ```python
  206. <str> = chr(<int>) # Converts int to unicode char.
  207. <int> = ord(<str>) # Converts unicode char to int.
  208. ```
  209. ```python
  210. >>> ord('0'), ord('9')
  211. (48, 57)
  212. >>> ord('A'), ord('Z')
  213. (65, 90)
  214. >>> ord('a'), ord('z')
  215. (97, 122)
  216. ```
  217. Regex
  218. -----
  219. ```python
  220. import re
  221. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  222. <list> = re.findall(<regex>, text) # Returns all occurrences.
  223. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  224. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  225. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  226. <Matches> = re.finditer(<regex>, text) # Searches for all occurrences of pattern.
  227. ```
  228. * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.**
  229. * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.**
  230. * **Use `r'\1'` or `'\\\\1'` for backreference.**
  231. * **Use `'?'` to make operators non-greedy.**
  232. ### Match Object
  233. ```python
  234. <str> = <Match>.group() # Whole match.
  235. <str> = <Match>.group(1) # Part in first bracket.
  236. <int> = <Match>.start() # Start index of a match.
  237. <int> = <Match>.end() # Exclusive end index of a match.
  238. ```
  239. ### Special Sequences
  240. **Use capital letter for negation.**
  241. ```python
  242. '\d' == '[0-9]' # Digit
  243. '\s' == '[ \t\n\r\f\v]' # Whitespace
  244. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  245. ```
  246. Print
  247. -----
  248. **Use `'file=sys.stderr'` for errors.**
  249. ```python
  250. print(<el_1> [, <el_2>, end='', sep='', file=<file>])
  251. ```
  252. ```python
  253. >>> from pprint import pprint
  254. >>> pprint(locals())
  255. {'__doc__': None,
  256. '__name__': '__main__',
  257. '__package__': None, ...}
  258. ```
  259. Format
  260. ------
  261. ```python
  262. <str> = f'{<el_1>}, {<el_2>}'
  263. <str> = '{}, {}'.format(<el_1>, <el_2>)
  264. ```
  265. ```python
  266. >>> Person = namedtuple('Person', 'name height')
  267. >>> person = Person('Jean-Luc', 187)
  268. >>> f'{person.height:10}'
  269. ' 187'
  270. >>> '{p.height:10}'.format(p=person)
  271. ' 187'
  272. ```
  273. ### General Options
  274. ```python
  275. {<el>:<10} # '<el> '
  276. {<el>:>10} # ' <el>'
  277. {<el>:^10} # ' <el> '
  278. {<el>:->10} # '------<el>'
  279. {<el>:>0} # '<el>'
  280. ```
  281. ### String Options
  282. **`'!r'` calls object's repr() method, instead of format(), to get a string.**
  283. ```python
  284. {'abcde'!r:<10} # "'abcde' "
  285. ```
  286. ```python
  287. {'abcde':.3} # 'abc'
  288. {'abcde':10.3} # 'abc '
  289. ```
  290. ### Number Options
  291. ```python
  292. {1.23456:.3f} # '1.235'
  293. {1.23456:10.3f} # ' 1.235'
  294. ```
  295. ```python
  296. { 123456:10,} # ' 123,456'
  297. { 123456:10_} # ' 123_456'
  298. { 123456:+10} # ' +123456'
  299. {-123456:=10} # '- 123456'
  300. { 123456: } # ' 123456'
  301. {-123456: } # '-123456'
  302. ```
  303. ```python
  304. {65:c} # 'A'
  305. {3:08b} # '00000011' -> Binary with leading zeros.
  306. {3:0<8b} # '11000000' -> Binary with trailing zeros.
  307. ```
  308. #### Float presentation types:
  309. * `'f'` - Fixed point: `.<precision>f`
  310. * `'%'` - Percent: `.<precision>%`
  311. * `'e'` - Exponent
  312. #### Integer presentation types:
  313. * `'c'` - Character
  314. * `'b'` - Binary
  315. * `'x'` - Hex
  316. * `'X'` - HEX
  317. Numbers
  318. -------
  319. ### Basic Functions
  320. ```python
  321. <num> = pow(<num>, <num>) # Or: <num> ** <num>
  322. <real> = abs(<num>)
  323. <real> = round(<real> [, ndigits])
  324. ```
  325. ### Constants
  326. ```python
  327. from math import e, pi
  328. ```
  329. ### Trigonometry
  330. ```python
  331. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  332. ```
  333. ### Logarithm
  334. ```python
  335. from math import log, log10, log2
  336. <float> = log(<real> [, base]) # Base e, if not specified.
  337. ```
  338. ### Infinity, nan
  339. ```python
  340. from math import inf, nan, isinf, isnan
  341. ```
  342. #### Or:
  343. ```python
  344. float('inf'), float('nan')
  345. ```
  346. ### Random
  347. ```python
  348. from random import random, randint, choice, shuffle
  349. <float> = random()
  350. <int> = randint(from_inclusive, to_inclusive)
  351. <el> = choice(<list>)
  352. shuffle(<list>)
  353. ```
  354. Datetime
  355. --------
  356. ```python
  357. from datetime import datetime, strptime
  358. now = datetime.now()
  359. now.month # 3
  360. now.strftime('%Y%m%d') # '20180315'
  361. now.strftime('%Y%m%d%H%M%S') # '20180315002834'
  362. <datetime> = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
  363. ```
  364. Arguments
  365. ---------
  366. **`'*'` is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.**
  367. ```python
  368. args = (1, 2)
  369. kwargs = {'x': 3, 'y': 4, 'z': 5}
  370. func(*args, **kwargs)
  371. ```
  372. #### Is the same as:
  373. ```python
  374. func(1, 2, x=3, y=4, z=5)
  375. ```
  376. #### Splat operator can also be used in function declarations:
  377. ```python
  378. def add(*a):
  379. return sum(a)
  380. ```
  381. ```python
  382. >>> add(1, 2, 3)
  383. 6
  384. ```
  385. #### And in few other places:
  386. ```python
  387. >>> a = (1, 2, 3)
  388. >>> [*a]
  389. [1, 2, 3]
  390. ```
  391. ```python
  392. >>> head, *body, tail = [1, 2, 3, 4]
  393. >>> body
  394. [2, 3]
  395. ```
  396. Inline
  397. ------
  398. ### Lambda
  399. ```python
  400. lambda: <return_value>
  401. lambda <argument_1>, <argument_2>: <return_value>
  402. ```
  403. ### Comprehension
  404. ```python
  405. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  406. <set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
  407. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  408. <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
  409. ```
  410. ```python
  411. out = [i+j for i in range(10) for j in range(10)]
  412. ```
  413. #### Is the same as:
  414. ```python
  415. out = []
  416. for i in range(10):
  417. for j in range(10):
  418. out.append(i+j)
  419. ```
  420. ### Map, Filter, Reduce
  421. ```python
  422. from functools import reduce
  423. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  424. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
  425. <int> = reduce(lambda out, x: out + x, range(10)) # 45
  426. ```
  427. ### Any, All
  428. ```python
  429. <bool> = any(<collection>) # False if empty.
  430. <bool> = all(el[1] for el in <collection>) # True if empty.
  431. ```
  432. ### If - Else
  433. ```python
  434. <expression_if_true> if <condition> else <expression_if_false>
  435. ```
  436. ```python
  437. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  438. ['zero', 1, 'zero', 3]
  439. ```
  440. ### Namedtuple, Enum, Class
  441. ```python
  442. from collections import namedtuple
  443. Point = namedtuple('Point', 'x y')
  444. point = Point(0, 0)
  445. ```
  446. ```python
  447. from enum import Enum
  448. Direction = Enum('Direction', 'n e s w')
  449. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  450. ```
  451. ```python
  452. # Warning: Objects will share the objects that are initialized in the dictionary!
  453. Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
  454. creature = Creature()
  455. ```
  456. Closure
  457. -------
  458. ```python
  459. def get_multiplier(a):
  460. def out(b):
  461. return a * b
  462. return out
  463. ```
  464. ```python
  465. >>> multiply_by_3 = get_multiplier(3)
  466. >>> multiply_by_3(10)
  467. 30
  468. ```
  469. #### Or:
  470. ```python
  471. from functools import partial
  472. <function> = partial(<function>, <argument_1> [, <argument_2>, ...])
  473. ```
  474. ```python
  475. >>> multiply_by_3 = partial(operator.mul, 3)
  476. >>> multiply_by_3(10)
  477. 30
  478. ```
  479. ### Nonlocal
  480. **If variable is assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.**
  481. ```python
  482. def get_counter():
  483. a = 0
  484. def out():
  485. nonlocal a
  486. a += 1
  487. return a
  488. return out
  489. ```
  490. ```python
  491. >>> counter = get_counter()
  492. >>> counter(), counter(), counter()
  493. (1, 2, 3)
  494. ```
  495. Decorator
  496. ---------
  497. **A decorator takes a function, adds some functionality and returns it.**
  498. ```python
  499. @decorator_name
  500. def function_that_gets_passed_to_decorator():
  501. ...
  502. ```
  503. ### Debugger Example
  504. **Decorator that prints function's name every time it gets called.**
  505. ```python
  506. from functools import wraps
  507. def debug(func):
  508. @wraps(func)
  509. def out(*args, **kwargs):
  510. print(func.__name__)
  511. return func(*args, **kwargs)
  512. return out
  513. @debug
  514. def add(x, y):
  515. return x + y
  516. ```
  517. * **Wraps is a helper decorator that copies metadata of function add() to function out().**
  518. * **Without it `'add.__name__'` would return `'out'`.**
  519. ### LRU Cache
  520. **Decorator that caches function's return values. All arguments must be hashable.**
  521. ```python
  522. from functools import lru_cache
  523. @lru_cache(maxsize=None)
  524. def fib(n):
  525. return n if n < 2 else fib(n-1) + fib(n-2)
  526. ```
  527. ```python
  528. >>> [fib(n) for n in range(10)]
  529. [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  530. >>> fib.cache_info()
  531. CacheInfo(hits=16, misses=10, maxsize=None, currsize=10)
  532. ```
  533. ### Parametrized Decorator
  534. ```python
  535. from functools import wraps
  536. def debug(print_result=False):
  537. def decorator(func):
  538. @wraps(func)
  539. def out(*args, **kwargs):
  540. result = func(*args, **kwargs)
  541. print(func.__name__, result if print_result else '')
  542. return result
  543. return out
  544. return decorator
  545. @debug(print_result=True)
  546. def add(x, y):
  547. return x + y
  548. ```
  549. Class
  550. -----
  551. ```python
  552. class <name>:
  553. def __init__(self, a):
  554. self.a = a
  555. def __repr__(self):
  556. class_name = type(self).__name__
  557. return f'{class_name}({self.a!r})'
  558. def __str__(self):
  559. return str(self.a)
  560. @classmethod
  561. def get_class_name(cls):
  562. return cls.__name__
  563. ```
  564. ### Constructor Overloading
  565. ```python
  566. class <name>:
  567. def __init__(self, a=None):
  568. self.a = a
  569. ```
  570. ### Inheritance
  571. ```python
  572. class Person:
  573. def __init__(self, name, age):
  574. self.name = name
  575. self.age = age
  576. class Employee(Person):
  577. def __init__(self, name, age, staff_num):
  578. super().__init__(name, age)
  579. self.staff_num = staff_num
  580. ```
  581. ### Comparable
  582. * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
  583. * **That means all objects compare not equal by default.**
  584. ```python
  585. class MyComparable:
  586. def __init__(self, a):
  587. self.a = a
  588. def __eq__(self, other):
  589. if isinstance(other, type(self)):
  590. return self.a == other.a
  591. return False
  592. ```
  593. ### Hashable
  594. * **Hashable object needs both hash() and eq() methods and it's hash value should never change.**
  595. * **Objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.**
  596. * **That is why Python automatically makes classes unhashable if you only implement eq().**
  597. ```python
  598. class MyHashable:
  599. def __init__(self, a):
  600. self.__a = copy.deepcopy(a)
  601. @property
  602. def a(self):
  603. return self.__a
  604. def __eq__(self, other):
  605. if isinstance(other, type(self)):
  606. return self.a == other.a
  607. return False
  608. def __hash__(self):
  609. return hash(self.a)
  610. ```
  611. ### Sequence
  612. ```python
  613. class MySequence:
  614. def __init__(self, a):
  615. self.a = a
  616. def __len__(self):
  617. return len(self.a)
  618. def __getitem__(self, i):
  619. return self.a[i]
  620. def __iter__(self):
  621. for el in self.a:
  622. yield el
  623. ```
  624. ### Callable
  625. ```python
  626. class Counter:
  627. def __init__(self):
  628. self.a = 0
  629. def __call__(self):
  630. self.a += 1
  631. return self.a
  632. ```
  633. ### Copy
  634. ```python
  635. from copy import copy, deepcopy
  636. <object> = copy(<object>)
  637. <object> = deepcopy(<object>)
  638. ```
  639. Enum
  640. ----
  641. ```python
  642. from enum import Enum, auto
  643. class <enum_name>(Enum):
  644. <member_name_1> = <value_1>
  645. <member_name_2> = <value_2_a>, <value_2_b>
  646. <member_name_3> = auto()
  647. @classmethod
  648. def get_member_names(cls):
  649. return [a.name for a in cls.__members__.values()]
  650. ```
  651. ```python
  652. <member> = <enum>.<member_name>
  653. <member> = <enum>['<member_name>']
  654. <member> = <enum>(<value>)
  655. name = <member>.name
  656. value = <member>.value
  657. ```
  658. ```python
  659. list_of_members = list(<enum>)
  660. member_names = [a.name for a in <enum>]
  661. member_values = [a.value for a in <enum>]
  662. random_member = random.choice(list(<enum>))
  663. ```
  664. ### Inline
  665. ```python
  666. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  667. Cutlery = Enum('Cutlery', 'knife fork spoon')
  668. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  669. ```
  670. #### Functions can not be values, so they must be wrapped:
  671. ```python
  672. from functools import partial
  673. LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
  674. 'OR' : partial(lambda l, r: l or r)})
  675. ```
  676. ```python
  677. >>> LogicOp.AND.value(True, False)
  678. False
  679. ```
  680. System
  681. ------
  682. ### Arguments
  683. ```python
  684. import sys
  685. script_name = sys.argv[0]
  686. arguments = sys.argv[1:]
  687. ```
  688. ### Read File
  689. ```python
  690. def read_file(filename):
  691. with open(filename, encoding='utf-8') as file:
  692. return file.readlines()
  693. ```
  694. ### Write to File
  695. ```python
  696. def write_to_file(filename, text):
  697. with open(filename, 'w', encoding='utf-8') as file:
  698. file.write(text)
  699. ```
  700. ### Path
  701. ```python
  702. from os import path, listdir
  703. <bool> = path.exists(<path>)
  704. <bool> = path.isfile(<path>)
  705. <bool> = path.isdir(<path>)
  706. <list> = listdir(<path>)
  707. ```
  708. ```python
  709. >>> from glob import glob
  710. >>> glob('../*.gif')
  711. ['1.gif', 'card.gif']
  712. ```
  713. ### Execute Command
  714. ```python
  715. import os
  716. <str> = os.popen(<command>).read()
  717. ```
  718. #### Or:
  719. ```python
  720. >>> import subprocess
  721. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  722. >>> a.stdout
  723. b'.\n..\nfile1.txt\nfile2.txt\n'
  724. >>> a.returncode
  725. 0
  726. ```
  727. ### Input
  728. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  729. ```python
  730. filename = input('Enter a file name: ')
  731. ```
  732. #### Prints lines until EOF:
  733. ```python
  734. while True:
  735. try:
  736. print(input())
  737. except EOFError:
  738. break
  739. ```
  740. ### Recursion Limit
  741. ```python
  742. >>> import sys
  743. >>> sys.getrecursionlimit()
  744. 1000
  745. >>> sys.setrecursionlimit(5000)
  746. ```
  747. JSON
  748. ----
  749. ```python
  750. import json
  751. ```
  752. ### Serialization
  753. ```python
  754. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  755. <dict> = json.loads(<str>)
  756. ```
  757. #### To preserve order:
  758. ```python
  759. from collections import OrderedDict
  760. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  761. ```
  762. ### Read File
  763. ```python
  764. def read_json_file(filename):
  765. with open(filename, encoding='utf-8') as file:
  766. return json.load(file)
  767. ```
  768. ### Write to File
  769. ```python
  770. def write_to_json_file(filename, an_object):
  771. with open(filename, 'w', encoding='utf-8') as file:
  772. json.dump(an_object, file, ensure_ascii=False, indent=2)
  773. ```
  774. SQLite
  775. ------
  776. ```python
  777. import sqlite3
  778. db = sqlite3.connect(<filename>)
  779. ...
  780. db.close()
  781. ```
  782. ### Read
  783. ```python
  784. cursor = db.execute(<query>)
  785. if cursor:
  786. <tuple> = cursor.fetchone() # First row.
  787. <list> = cursor.fetchall() # Remaining rows.
  788. ```
  789. ### Write
  790. ```python
  791. db.execute(<query>)
  792. db.commit()
  793. ```
  794. Pickle
  795. ------
  796. ```python
  797. >>> import pickle
  798. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  799. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  800. >>> pickle.load(open('data.p', 'rb'))
  801. {'lion': 'yellow', 'kitty': 'red'}
  802. ```
  803. Exceptions
  804. ----------
  805. ```python
  806. while True:
  807. try:
  808. x = int(input('Please enter a number: '))
  809. except ValueError:
  810. print('Oops! That was no valid number. Try again...')
  811. else:
  812. print('Thank you.')
  813. break
  814. ```
  815. #### Raising exception:
  816. ```python
  817. raise ValueError('A very specific message!')
  818. ```
  819. ### Finally
  820. ```python
  821. >>> try:
  822. ... raise KeyboardInterrupt
  823. ... finally:
  824. ... print('Goodbye, world!')
  825. Goodbye, world!
  826. Traceback (most recent call last):
  827. File "<stdin>", line 2, in <module>
  828. KeyboardInterrupt
  829. ```
  830. Bytes
  831. -----
  832. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  833. ```python
  834. <bytes> = b'<str>'
  835. <int> = <bytes>[<index>]
  836. <bytes> = <bytes>[<slice>]
  837. <bytes> = b''.join(<coll_of_bytes>)
  838. ```
  839. ### Encode
  840. ```python
  841. <bytes> = <str>.encode(encoding='utf-8')
  842. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  843. <bytes> = bytes.fromhex(<hex>)
  844. ```
  845. ### Decode
  846. ```python
  847. <str> = <bytes>.decode('utf-8')
  848. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  849. <hex> = <bytes>.hex()
  850. ```
  851. ### Read Bytes from File
  852. ```python
  853. def read_bytes(filename):
  854. with open(filename, 'rb') as file:
  855. return file.read()
  856. ```
  857. ### Write Bytes to File
  858. ```python
  859. def write_bytes(filename, bytes_obj):
  860. with open(filename, 'wb') as file:
  861. file.write(bytes_obj)
  862. ```
  863. Struct
  864. ------
  865. * **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.**
  866. * **Machine’s native type sizes and byte order are used by default.**
  867. ```python
  868. from struct import pack, unpack, calcsize
  869. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  870. <tuple> = unpack('<format>', <bytes>)
  871. ```
  872. ### Example
  873. ```python
  874. >>> pack('>hhl', 1, 2, 3)
  875. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  876. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  877. (1, 2, 3)
  878. >>> calcsize('>hhl')
  879. 8
  880. ```
  881. ### Format
  882. #### For standard sizes start format string with:
  883. * `'='` - native byte order
  884. * `'<'` - little-endian
  885. * `'>'` - big-endian
  886. #### Use capital leter for unsigned type. Standard size in brackets:
  887. * `'x'` - pad byte
  888. * `'c'` - char (1)
  889. * `'h'` - short (2)
  890. * `'i'` - int (4)
  891. * `'l'` - long (4)
  892. * `'q'` - long long (8)
  893. * `'f'` - float (4)
  894. * `'d'` - double (8)
  895. Array
  896. -----
  897. **List that can only hold elements of predefined type. Available types are listed above.**
  898. ```python
  899. from array import array
  900. <array> = array(<typecode> [, <collection>])
  901. ```
  902. Deque
  903. -----
  904. **Short for “double-ended queue” and pronounced “deck”. It is a thread-safe list with efficient appends and pops from either side.**
  905. ```python
  906. from collections import deque
  907. <deque> = deque(<collection>, maxlen=None)
  908. ```
  909. ```python
  910. <deque>.appendleft(<el>)
  911. <deque>.extendleft(<collection>) # Collection gets reversed.
  912. <el> = <deque>.popleft()
  913. <deque>.rotate(n=1) # Rotates elements to the right.
  914. ```
  915. Threading
  916. ---------
  917. ```python
  918. from threading import Thread, RLock
  919. ```
  920. ### Thread
  921. ```python
  922. thread = Thread(target=<function>, args=(<first_arg>, ))
  923. thread.start()
  924. ...
  925. thread.join()
  926. ```
  927. ### Lock
  928. ```python
  929. lock = RLock()
  930. lock.acquire()
  931. ...
  932. lock.release()
  933. ```
  934. Hashlib
  935. -------
  936. ```python
  937. >>> import hashlib
  938. >>> hashlib.md5(<str>.encode()).hexdigest()
  939. '33d0eba106da4d3ebca17fcd3f4c3d77'
  940. ```
  941. Itertools
  942. ---------
  943. **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!**
  944. ```python
  945. from itertools import *
  946. ```
  947. ### Combinatoric iterators
  948. ```python
  949. >>> combinations('abc', 2)
  950. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  951. >>> combinations_with_replacement('abc', 2)
  952. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  953. ('b', 'b'), ('b', 'c'),
  954. ('c', 'c')]
  955. >>> permutations('abc', 2)
  956. [('a', 'b'), ('a', 'c'),
  957. ('b', 'a'), ('b', 'c'),
  958. ('c', 'a'), ('c', 'b')]
  959. >>> product('ab', [1, 2])
  960. [('a', 1), ('a', 2),
  961. ('b', 1), ('b', 2)]
  962. >>> product([0, 1], repeat=3)
  963. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  964. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  965. ```
  966. ### Infinite iterators
  967. ```python
  968. >>> i = count(5, 2)
  969. >>> next(i), next(i), next(i)
  970. (5, 7, 9)
  971. >>> a = cycle('abc')
  972. >>> [next(a) for _ in range(10)]
  973. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  974. >>> repeat(10, 3)
  975. [10, 10, 10]
  976. ```
  977. ### Iterators
  978. ```python
  979. >>> chain([1, 2], range(3, 5))
  980. [1, 2, 3, 4]
  981. >>> compress('abc', [True, 0, 1])
  982. ['a', 'c']
  983. >>> # islice(<collection>, from_inclusive, to_exclusive)
  984. >>> islice([1, 2, 3], 1, None)
  985. [2, 3]
  986. >>> people = [{'id': 1, 'name': 'Bob'},
  987. {'id': 2, 'name': 'Bob'},
  988. {'id': 3, 'name': 'Peter'}]
  989. >>> groups = groupby(people, key=lambda a: a['name'])
  990. >>> {name: list(group) for name, group in groups}
  991. {'Bob': [{'id': 1, 'name': 'Bob'},
  992. {'id': 2, 'name': 'Bob'}],
  993. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  994. ```
  995. Introspection and Metaprograming
  996. --------------------------------
  997. **Inspecting code at runtime and code that generates code. You can:**
  998. * **Look at the attributes**
  999. * **Set new attributes**
  1000. * **Create functions dynamically**
  1001. * **Traverse the parent classes**
  1002. * **Change values in the class**
  1003. ### Variables
  1004. ```python
  1005. <list> = dir() # Names of in-scope variables.
  1006. <dict> = locals() # Dict of local variables. Also vars().
  1007. <dict> = globals() # Dict of global variables.
  1008. ```
  1009. ### Attributes
  1010. ```python
  1011. class Z:
  1012. def __init__(self):
  1013. self.a = 'abcde'
  1014. self.b = 12345
  1015. ```
  1016. ```python
  1017. >>> z = Z()
  1018. >>> vars(z)
  1019. {'a': 'abcde', 'b': 12345}
  1020. >>> getattr(z, 'a')
  1021. 'abcde'
  1022. >>> hasattr(z, 'c')
  1023. False
  1024. >>> setattr(z, 'c', 10)
  1025. ```
  1026. ### Parameters
  1027. ```python
  1028. from inspect import signature
  1029. sig = signature(<function>)
  1030. no_of_params = len(sig.parameters)
  1031. param_names = list(sig.parameters.keys())
  1032. ```
  1033. ### Type
  1034. **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!).**
  1035. ```python
  1036. type(<class_name>, <parents_tuple>, <attributes_dict>)
  1037. ```
  1038. ```python
  1039. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1040. >>> z = Z()
  1041. ```
  1042. ### Meta Class
  1043. **Class that creates class.**
  1044. ```python
  1045. def my_meta_class(name, parents, attrs):
  1046. attrs['a'] = 'abcde'
  1047. return type(name, parents, attrs)
  1048. ```
  1049. #### Or:
  1050. ```python
  1051. class MyMetaClass(type):
  1052. def __new__(cls, name, parents, attrs):
  1053. attrs['a'] = 'abcde'
  1054. return type.__new__(cls, name, parents, attrs)
  1055. ```
  1056. ### Metaclass Attribute
  1057. **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.**
  1058. ```python
  1059. class MyClass(metaclass=MyMetaClass):
  1060. def __init__(self):
  1061. self.b = 12345
  1062. ```
  1063. Operator
  1064. --------
  1065. ```python
  1066. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  1067. eq, ne, lt, le, gt, ge, \
  1068. not_, and_, or_, \
  1069. itemgetter, attrgetter, methodcaller
  1070. ```
  1071. ```python
  1072. import operator as op
  1073. product_of_elems = functools.reduce(op.mul, <list>)
  1074. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1075. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1076. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1077. last_el = op.methodcaller('pop')(<list>)
  1078. ```
  1079. Eval
  1080. ----
  1081. ### Basic
  1082. ```python
  1083. >>> from ast import literal_eval
  1084. >>> literal_eval('1 + 2')
  1085. 3
  1086. >>> literal_eval('[1, 2, 3]')
  1087. [1, 2, 3]
  1088. >>> ast.literal_eval('abs(1)')
  1089. ValueError: malformed node or string
  1090. ```
  1091. ### Using Abstract Syntax Trees
  1092. ```python
  1093. import ast
  1094. from ast import Num, BinOp, UnaryOp
  1095. import operator as op
  1096. legal_operators = {ast.Add: op.add,
  1097. ast.Sub: op.sub,
  1098. ast.Mult: op.mul,
  1099. ast.Div: op.truediv,
  1100. ast.Pow: op.pow,
  1101. ast.BitXor: op.xor,
  1102. ast.USub: op.neg}
  1103. def evaluate(expression):
  1104. root = ast.parse(expression, mode='eval')
  1105. return eval_node(root.body)
  1106. def eval_node(node):
  1107. node_type = type(node)
  1108. if node_type == Num:
  1109. return node.n
  1110. if node_type not in [BinOp, UnaryOp]:
  1111. raise TypeError(node)
  1112. operator_type = type(node.op)
  1113. if operator_type not in legal_operators:
  1114. raise TypeError(f'Illegal operator {node.op}')
  1115. operator = legal_operators[operator_type]
  1116. if node_type == BinOp:
  1117. left, right = eval_node(node.left), eval_node(node.right)
  1118. return operator(left, right)
  1119. elif node_type == UnaryOp:
  1120. operand = eval_node(node.operand)
  1121. return operator(operand)
  1122. ```
  1123. ```python
  1124. >>> evaluate('2 ^ 6')
  1125. 4
  1126. >>> evaluate('2 ** 6')
  1127. 64
  1128. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1129. -5.0
  1130. ```
  1131. Coroutine
  1132. ---------
  1133. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1134. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1135. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1136. ### Helper Decorator
  1137. * **All coroutines must be "primed" by first calling next().**
  1138. * **Remembering to call next() is easy to forget.**
  1139. * **Solved by wrapping coroutines with a decorator:**
  1140. ```python
  1141. def coroutine(func):
  1142. def out(*args, **kwargs):
  1143. cr = func(*args, **kwargs)
  1144. next(cr)
  1145. return cr
  1146. return out
  1147. ```
  1148. ### Pipeline Example
  1149. ```python
  1150. def reader(target):
  1151. for i in range(10):
  1152. target.send(i)
  1153. target.close()
  1154. @coroutine
  1155. def adder(target):
  1156. while True:
  1157. item = (yield)
  1158. target.send(item + 100)
  1159. @coroutine
  1160. def printer():
  1161. while True:
  1162. item = (yield)
  1163. print(item)
  1164. reader(adder(printer())) # 100, 101, ..., 109
  1165. ```
  1166. <br><br>
  1167. Libraries
  1168. =========
  1169. Argparse
  1170. --------
  1171. ```python
  1172. from argparse import ArgumentParser
  1173. parser = ArgumentParser(description='calculate X to the power of Y')
  1174. group = parser.add_mutually_exclusive_group()
  1175. group.add_argument('-v', '--verbose', action='store_true')
  1176. group.add_argument('-q', '--quiet', action='store_true')
  1177. parser.add_argument('x', type=int, help='the base')
  1178. parser.add_argument('y', type=int, help='the exponent')
  1179. args = parser.parse_args()
  1180. answer = args.x ** args.y
  1181. if args.quiet:
  1182. print(answer)
  1183. elif args.verbose:
  1184. print(f'{args.x} to the power {args.y} equals {answer}')
  1185. else:
  1186. print(f'{args.x}^{args.y} == {answer}')
  1187. ```
  1188. ### Usage
  1189. ```text
  1190. $ python3 prog.py --help
  1191. usage: test2.py [-h] [-v | -q] x y
  1192. calculate X to the power of Y
  1193. positional arguments:
  1194. x the base
  1195. y the exponent
  1196. optional arguments:
  1197. -h, --help show this help message and exit
  1198. -v, --verbose
  1199. -q, --quiet
  1200. ```
  1201. Progress Bar
  1202. ------------
  1203. ```python
  1204. # $ pip3 install tqdm
  1205. from tqdm import tqdm
  1206. from time import sleep
  1207. for i in tqdm([1, 2, 3]):
  1208. sleep(0.2)
  1209. for i in tqdm(range(100)):
  1210. sleep(0.02)
  1211. ```
  1212. Table
  1213. -----
  1214. #### Prints CSV file as ASCII table:
  1215. ```python
  1216. # $ pip3 install tabulate
  1217. from csv import reader
  1218. from tabulate import tabulate
  1219. with open(<filename>, encoding='utf-8', newline='') as csv_file:
  1220. reader = reader(csv_file, delimiter=';')
  1221. headers = [a.title() for a in next(reader)]
  1222. print(tabulate(reader, headers))
  1223. ```
  1224. Curses
  1225. ------
  1226. ```python
  1227. # $ pip3 install curses
  1228. from curses import wrapper
  1229. def main():
  1230. wrapper(draw)
  1231. def draw(screen):
  1232. screen.clear()
  1233. screen.addstr(0, 0, 'Press ESC to quit.')
  1234. while screen.getch() != 27:
  1235. pass
  1236. def get_border(screen):
  1237. from collections import namedtuple
  1238. P = namedtuple('P', 'x y')
  1239. height, width = screen.getmaxyx()
  1240. return P(width - 1, height - 1)
  1241. ```
  1242. Plot
  1243. ----
  1244. ```python
  1245. # $ pip3 install matplotlib
  1246. from matplotlib import pyplot
  1247. pyplot.plot(<data_1> [, <data_2>, ...])
  1248. pyplot.savefig(<filename>, transparent=True)
  1249. pyplot.show()
  1250. ```
  1251. Image
  1252. -----
  1253. #### Creates PNG image of greyscale gradient:
  1254. ```python
  1255. # $ pip3 install pillow
  1256. from PIL import Image
  1257. width, height = 100, 100
  1258. img = Image.new('L', (width, height), 'white')
  1259. img.putdata([255*a/(width*height) for a in range(width*height)])
  1260. img.save('out.png')
  1261. ```
  1262. ### Modes
  1263. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1264. * `'L'` - 8-bit pixels, greyscale.
  1265. * `'RGB'` - 3x8-bit pixels, true color.
  1266. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1267. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1268. Audio
  1269. -----
  1270. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1271. ```python
  1272. import wave, struct
  1273. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1274. wf = wave.open(<filename>, 'wb')
  1275. wf.setnchannels(1)
  1276. wf.setsampwidth(4)
  1277. wf.setframerate(44100)
  1278. wf.writeframes(b''.join(frames))
  1279. wf.close()
  1280. ```
  1281. Url
  1282. ---
  1283. ```python
  1284. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1285. ```
  1286. ### Encode
  1287. ```python
  1288. >>> quote("Can't be in URL!")
  1289. 'Can%27t%20be%20in%20URL%21'
  1290. >>> quote_plus("Can't be in URL!")
  1291. 'Can%27t+be+in+URL%21'
  1292. ```
  1293. ### Decode
  1294. ```python
  1295. >>> unquote('Can%27t+be+in+URL%21')
  1296. "Can't+be+in+URL!"
  1297. >>> unquote_plus('Can%27t+be+in+URL%21')
  1298. "Can't be in URL!"
  1299. ```
  1300. Scraping
  1301. --------
  1302. ```python
  1303. # $ pip3 install requests beautifulsoup4
  1304. >>> import requests
  1305. >>> from bs4 import BeautifulSoup
  1306. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1307. >>> page = requests.get(url)
  1308. >>> document = BeautifulSoup(page.text, 'html.parser')
  1309. >>> table = document.find('table', class_='infobox vevent')
  1310. >>> rows = table.find_all('tr')
  1311. >>> link = rows[11].find('a')['href']
  1312. 'https://www.python.org/'
  1313. >>> latest_v = rows[6].find('div').text.split()[0]
  1314. '3.7.2'
  1315. ```
  1316. Web
  1317. ---
  1318. ```python
  1319. # $ pip3 install bottle
  1320. from bottle import run, route, post, template, request, response
  1321. import json
  1322. ```
  1323. ### Run
  1324. ```python
  1325. run(host='localhost', port=8080)
  1326. run(host='0.0.0.0', port=80, server='cherrypy')
  1327. ```
  1328. ### Static Request
  1329. ```python
  1330. @route('/img/<image>')
  1331. def send_image(image):
  1332. return static_file(image, 'images/', mimetype='image/png')
  1333. ```
  1334. ### Dynamic Request
  1335. ```python
  1336. @route('/<sport>')
  1337. def send_page(sport):
  1338. return template('<h1>{{title}}</h1>', title=sport)
  1339. ```
  1340. ### REST Request
  1341. ```python
  1342. @post('/odds/<sport>')
  1343. def odds_handler(sport):
  1344. team = request.forms.get('team')
  1345. home_odds, away_odds = 2.44, 3.29
  1346. response.headers['Content-Type'] = 'application/json'
  1347. response.headers['Cache-Control'] = 'no-cache'
  1348. return json.dumps([team, home_odds, away_odds])
  1349. ```
  1350. #### Test:
  1351. ```python
  1352. # $ pip3 install requests
  1353. >>> import requests
  1354. >>> url = 'http://localhost:8080/odds/football'
  1355. >>> r = requests.post(url, data={'team': 'arsenal f.c.'})
  1356. >>> r.json()
  1357. ['arsenal f.c.', 2.44, 3.29]
  1358. ```
  1359. Profile
  1360. -------
  1361. ### Basic
  1362. ```python
  1363. from time import time
  1364. start_time = time() # Seconds since Epoch.
  1365. ...
  1366. duration = time() - start_time
  1367. ```
  1368. ### High Performance
  1369. ```python
  1370. from time import perf_counter as pc
  1371. start_time = pc() # Seconds since restart.
  1372. ...
  1373. duration = pc() - start_time
  1374. ```
  1375. ### Timing a Snippet
  1376. ```python
  1377. from timeit import timeit
  1378. timeit('"-".join(str(a) for a in range(100))',
  1379. number=10000, globals=globals(), setup='pass')
  1380. ```
  1381. ### Line Profiler
  1382. ```python
  1383. # $ pip3 install line_profiler
  1384. @profile
  1385. def main():
  1386. a = [*range(10000)]
  1387. b = {*range(10000)}
  1388. main()
  1389. ```
  1390. #### Usage:
  1391. ```text
  1392. $ kernprof -lv test.py
  1393. Line # Hits Time Per Hit % Time Line Contents
  1394. ==============================================================
  1395. 1 @profile
  1396. 2 def main():
  1397. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1398. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1399. ```
  1400. ### Call Graph
  1401. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1402. ```python
  1403. # $ pip3 install pycallgraph
  1404. from pycallgraph import output, PyCallGraph
  1405. from datetime import datetime
  1406. graph = output.GraphvizOutput()
  1407. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1408. graph.output_file = f'profile-{time_str}.png'
  1409. with PyCallGraph(output=graph):
  1410. <code_to_be_profiled>
  1411. ```
  1412. NumPy
  1413. -----
  1414. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1415. ```python
  1416. # $ pip3 install numpy
  1417. import numpy as np
  1418. ```
  1419. **Shape is a tuple of ints, representing sizes of array's dimensions.**
  1420. ```python
  1421. <array> = np.array(<list>)
  1422. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1423. <array> = np.ones(<shape>)
  1424. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1425. ```
  1426. ```python
  1427. <array>.shape = <shape>
  1428. <view> = <array>.reshape(<shape>)
  1429. <view> = np.broadcast_to(<array>, <shape>)
  1430. ```
  1431. ```python
  1432. <el_or_array> = <array>.sum([<axis>]) # Axis is an index of dimension that gets collapsed.
  1433. <el_or_array> = <array>.argmin([<axis>]) # Returns index/es of smallest element/s.
  1434. ```
  1435. ### Indexing
  1436. #### Basic indexing:
  1437. ```bash
  1438. <el> = <2d_array>[0, 0]
  1439. ```
  1440. #### Basic slicing:
  1441. ```bash
  1442. <1d_view> = <2d_array>[0] # First row.
  1443. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  1444. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  1445. ```
  1446. #### Integer array indexing:
  1447. **If row and column indexes differ in shape, they are combined with broadcasting.**
  1448. ```bash
  1449. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  1450. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  1451. ```
  1452. #### Boolean array indexing:
  1453. ```bash
  1454. <2d_bool_array> = <2d_array> > 0
  1455. <1d_array> = <2d_array>[<2d_bool_array>]
  1456. ```
  1457. ### Broadcasting
  1458. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1459. ```python
  1460. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1461. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1462. ```
  1463. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1464. ```python
  1465. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1466. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1467. ```
  1468. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1469. ```python
  1470. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1471. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1472. ```
  1473. #### 3. If neither non-matching dimension has size 1, rise an error.
  1474. ### Example
  1475. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1476. ```python
  1477. >>> points = np.array([0.1, 0.6, 0.8])
  1478. [ 0.1, 0.6, 0.8]
  1479. >>> wrapped_points = points.reshape(3, 1)
  1480. [[ 0.1],
  1481. [ 0.6],
  1482. [ 0.8]]
  1483. >>> distances = wrapped_points - points
  1484. [[ 0. , -0.5, -0.7],
  1485. [ 0.5, 0. , -0.2],
  1486. [ 0.7, 0.2, 0. ]]
  1487. >>> distances = np.abs(distances)
  1488. [[ 0. , 0.5, 0.7],
  1489. [ 0.5, 0. , 0.2],
  1490. [ 0.7, 0.2, 0. ]]
  1491. >>> i = np.arange(3)
  1492. [0, 1, 2]
  1493. >>> distances[i, i] = np.inf
  1494. [[ inf, 0.5, 0.7],
  1495. [ 0.5, inf, 0.2],
  1496. [ 0.7, 0.2, inf]]
  1497. >>> distances.argmin(1)
  1498. [1, 2, 1]
  1499. ```
  1500. Basic Script Template
  1501. ---------------------
  1502. ```python
  1503. #!/usr/bin/env python3
  1504. #
  1505. # Usage: .py
  1506. #
  1507. from collections import namedtuple
  1508. from enum import Enum
  1509. import re
  1510. import sys
  1511. def main():
  1512. pass
  1513. ###
  1514. ## UTIL
  1515. #
  1516. def read_file(filename):
  1517. with open(filename, encoding='utf-8') as file:
  1518. return file.readlines()
  1519. if __name__ == '__main__':
  1520. main()
  1521. ```