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.

1838 lines
39 KiB

6 years ago
7 years ago
5 years ago
5 years ago
7 years ago
6 years ago
6 years ago
5 years ago
7 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
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
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
5 years ago
5 years ago
5 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
7 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
5 years ago
7 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
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
7 years ago
6 years ago
7 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
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
5 years ago
6 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
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
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
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
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
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
6 years ago
6 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
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
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
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
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
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
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
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
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
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
5 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
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
6 years ago
6 years ago
6 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
5 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
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
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
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
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
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
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
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
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(<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. System
  677. ------
  678. ### Arguments
  679. ```python
  680. import sys
  681. script_name = sys.argv[0]
  682. arguments = sys.argv[1:]
  683. ```
  684. ### Read File
  685. ```python
  686. def read_file(filename):
  687. with open(filename, encoding='utf-8') as file:
  688. return file.readlines()
  689. ```
  690. ### Write to File
  691. ```python
  692. def write_to_file(filename, text):
  693. with open(filename, 'w', encoding='utf-8') as file:
  694. file.write(text)
  695. ```
  696. ### Path
  697. ```python
  698. from os import path, listdir
  699. <bool> = path.exists(<path>)
  700. <bool> = path.isfile(<path>)
  701. <bool> = path.isdir(<path>)
  702. <list> = listdir(<path>)
  703. ```
  704. ```python
  705. >>> from glob import glob
  706. >>> glob('../*.gif')
  707. ['1.gif', 'card.gif']
  708. ```
  709. ### Execute Command
  710. ```python
  711. import os
  712. <str> = os.popen(<command>).read()
  713. ```
  714. #### Or:
  715. ```python
  716. >>> import subprocess
  717. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  718. >>> a.stdout
  719. b'.\n..\nfile1.txt\nfile2.txt\n'
  720. >>> a.returncode
  721. 0
  722. ```
  723. ### Input
  724. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  725. ```python
  726. filename = input('Enter a file name: ')
  727. ```
  728. #### Prints lines until EOF:
  729. ```python
  730. while True:
  731. try:
  732. print(input())
  733. except EOFError:
  734. break
  735. ```
  736. ### Recursion Limit
  737. ```python
  738. >>> import sys
  739. >>> sys.getrecursionlimit()
  740. 1000
  741. >>> sys.setrecursionlimit(5000)
  742. ```
  743. JSON
  744. ----
  745. ```python
  746. import json
  747. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  748. <dict> = json.loads(<str>)
  749. ```
  750. #### To preserve order:
  751. ```python
  752. from collections import OrderedDict
  753. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  754. ```
  755. ### Read File
  756. ```python
  757. def read_json_file(filename):
  758. with open(filename, encoding='utf-8') as file:
  759. return json.load(file)
  760. ```
  761. ### Write to File
  762. ```python
  763. def write_to_json_file(filename, an_object):
  764. with open(filename, 'w', encoding='utf-8') as file:
  765. json.dump(an_object, file, ensure_ascii=False, indent=2)
  766. ```
  767. SQLite
  768. ------
  769. ```python
  770. import sqlite3
  771. db = sqlite3.connect(<filename>)
  772. ...
  773. db.close()
  774. ```
  775. ### Read
  776. ```python
  777. cursor = db.execute(<query>)
  778. if cursor:
  779. <tuple> = cursor.fetchone() # First row.
  780. <list> = cursor.fetchall() # Remaining rows.
  781. ```
  782. ### Write
  783. ```python
  784. db.execute(<query>)
  785. db.commit()
  786. ```
  787. Pickle
  788. ------
  789. ```python
  790. import pickle
  791. <bytes> = pickle.dumps(<object>)
  792. <object> = pickle.loads(<bytes>)
  793. ```
  794. ### Read Object from File
  795. ```python
  796. def read_pickle_file(filename):
  797. with open(filename, 'rb') as file:
  798. return pickle.load(file)
  799. ```
  800. ### Write Object to File
  801. ```python
  802. def write_to_pickle_file(filename, an_object):
  803. with open(filename, 'wb') as file:
  804. pickle.dump(an_object, file)
  805. ```
  806. Exceptions
  807. ----------
  808. ```python
  809. while True:
  810. try:
  811. x = int(input('Please enter a number: '))
  812. except ValueError:
  813. print('Oops! That was no valid number. Try again...')
  814. else:
  815. print('Thank you.')
  816. break
  817. ```
  818. #### Raising exception:
  819. ```python
  820. raise ValueError('A very specific message!')
  821. ```
  822. ### Finally
  823. ```python
  824. >>> try:
  825. ... raise KeyboardInterrupt
  826. ... finally:
  827. ... print('Goodbye, world!')
  828. Goodbye, world!
  829. Traceback (most recent call last):
  830. File "<stdin>", line 2, in <module>
  831. KeyboardInterrupt
  832. ```
  833. Bytes
  834. -----
  835. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  836. ```python
  837. <bytes> = b'<str>'
  838. <int> = <bytes>[<index>]
  839. <bytes> = <bytes>[<slice>]
  840. <bytes> = b''.join(<coll_of_bytes>)
  841. ```
  842. ### Encode
  843. ```python
  844. <bytes> = <str>.encode(encoding='utf-8')
  845. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  846. <bytes> = bytes.fromhex(<hex>)
  847. ```
  848. ### Decode
  849. ```python
  850. <str> = <bytes>.decode('utf-8')
  851. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  852. <hex> = <bytes>.hex()
  853. ```
  854. ### Read Bytes from File
  855. ```python
  856. def read_bytes(filename):
  857. with open(filename, 'rb') as file:
  858. return file.read()
  859. ```
  860. ### Write Bytes to File
  861. ```python
  862. def write_bytes(filename, bytes_obj):
  863. with open(filename, 'wb') as file:
  864. file.write(bytes_obj)
  865. ```
  866. Struct
  867. ------
  868. * **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.**
  869. * **Machine’s native type sizes and byte order are used by default.**
  870. ```python
  871. from struct import pack, unpack, calcsize
  872. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  873. <tuple> = unpack('<format>', <bytes>)
  874. ```
  875. ### Example
  876. ```python
  877. >>> pack('>hhl', 1, 2, 3)
  878. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  879. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  880. (1, 2, 3)
  881. >>> calcsize('>hhl')
  882. 8
  883. ```
  884. ### Format
  885. #### For standard sizes start format string with:
  886. * `'='` - native byte order
  887. * `'<'` - little-endian
  888. * `'>'` - big-endian
  889. #### Use capital leter for unsigned type. Standard size in brackets:
  890. * `'x'` - pad byte
  891. * `'c'` - char (1)
  892. * `'h'` - short (2)
  893. * `'i'` - int (4)
  894. * `'l'` - long (4)
  895. * `'q'` - long long (8)
  896. * `'f'` - float (4)
  897. * `'d'` - double (8)
  898. Array
  899. -----
  900. **List that can only hold elements of predefined type. Available types are listed above.**
  901. ```python
  902. from array import array
  903. <array> = array(<typecode> [, <collection>])
  904. ```
  905. Deque
  906. -----
  907. **A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.**
  908. ```python
  909. from collections import deque
  910. <deque> = deque(<collection>, maxlen=None)
  911. ```
  912. ```python
  913. <deque>.appendleft(<el>)
  914. <deque>.extendleft(<collection>) # Collection gets reversed.
  915. <el> = <deque>.popleft()
  916. <deque>.rotate(n=1) # Rotates elements to the right.
  917. ```
  918. Threading
  919. ---------
  920. ```python
  921. from threading import Thread, RLock
  922. ```
  923. ### Thread
  924. ```python
  925. thread = Thread(target=<function>, args=(<first_arg>, ))
  926. thread.start()
  927. ...
  928. thread.join()
  929. ```
  930. ### Lock
  931. ```python
  932. lock = RLock()
  933. lock.acquire()
  934. ...
  935. lock.release()
  936. ```
  937. Hashlib
  938. -------
  939. ```python
  940. >>> import hashlib
  941. >>> hashlib.md5(<str>.encode()).hexdigest()
  942. '33d0eba106da4d3ebca17fcd3f4c3d77'
  943. ```
  944. Itertools
  945. ---------
  946. * **Every function returns an iterator and can accept any collection and/or iterator.**
  947. * **If you want to print the iterator, you need to pass it to the list() function!**
  948. ```python
  949. from itertools import *
  950. ```
  951. ### Combinatoric iterators
  952. ```python
  953. >>> combinations('abc', 2)
  954. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  955. >>> combinations_with_replacement('abc', 2)
  956. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  957. ('b', 'b'), ('b', 'c'),
  958. ('c', 'c')]
  959. >>> permutations('abc', 2)
  960. [('a', 'b'), ('a', 'c'),
  961. ('b', 'a'), ('b', 'c'),
  962. ('c', 'a'), ('c', 'b')]
  963. >>> product('ab', [1, 2])
  964. [('a', 1), ('a', 2),
  965. ('b', 1), ('b', 2)]
  966. >>> product([0, 1], repeat=3)
  967. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  968. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  969. ```
  970. ### Infinite iterators
  971. ```python
  972. >>> i = count(5, 2)
  973. >>> next(i), next(i), next(i)
  974. (5, 7, 9)
  975. >>> a = cycle('abc')
  976. >>> [next(a) for _ in range(10)]
  977. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  978. >>> repeat(10, 3)
  979. [10, 10, 10]
  980. ```
  981. ### Iterators
  982. ```python
  983. >>> chain([1, 2], range(3, 5))
  984. [1, 2, 3, 4]
  985. >>> compress('abc', [True, 0, 1])
  986. ['a', 'c']
  987. >>> # islice(<collection>, from_inclusive, to_exclusive)
  988. >>> islice([1, 2, 3], 1, None)
  989. [2, 3]
  990. >>> people = [{'id': 1, 'name': 'Bob'},
  991. {'id': 2, 'name': 'Bob'},
  992. {'id': 3, 'name': 'Peter'}]
  993. >>> groups = groupby(people, key=lambda a: a['name'])
  994. >>> {name: list(group) for name, group in groups}
  995. {'Bob': [{'id': 1, 'name': 'Bob'},
  996. {'id': 2, 'name': 'Bob'}],
  997. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  998. ```
  999. Introspection and Metaprograming
  1000. --------------------------------
  1001. **Inspecting code at runtime and code that generates code. You can:**
  1002. * **Look at the attributes**
  1003. * **Set new attributes**
  1004. * **Create functions dynamically**
  1005. * **Traverse the parent classes**
  1006. * **Change values in the class**
  1007. ### Variables
  1008. ```python
  1009. <list> = dir() # Names of in-scope variables.
  1010. <dict> = locals() # Dict of local variables. Also vars().
  1011. <dict> = globals() # Dict of global variables.
  1012. ```
  1013. ### Attributes
  1014. ```python
  1015. class Z:
  1016. def __init__(self):
  1017. self.a = 'abcde'
  1018. self.b = 12345
  1019. ```
  1020. ```python
  1021. >>> z = Z()
  1022. >>> vars(z)
  1023. {'a': 'abcde', 'b': 12345}
  1024. >>> getattr(z, 'a')
  1025. 'abcde'
  1026. >>> hasattr(z, 'c')
  1027. False
  1028. >>> setattr(z, 'c', 10)
  1029. ```
  1030. ### Parameters
  1031. ```python
  1032. from inspect import signature
  1033. sig = signature(<function>)
  1034. no_of_params = len(sig.parameters)
  1035. param_names = list(sig.parameters.keys())
  1036. ```
  1037. ### Type
  1038. **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!).**
  1039. ```python
  1040. type(<class_name>, <parents_tuple>, <attributes_dict>)
  1041. ```
  1042. ```python
  1043. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1044. >>> z = Z()
  1045. ```
  1046. ### Meta Class
  1047. **Class that creates class.**
  1048. ```python
  1049. def my_meta_class(name, parents, attrs):
  1050. attrs['a'] = 'abcde'
  1051. return type(name, parents, attrs)
  1052. ```
  1053. #### Or:
  1054. ```python
  1055. class MyMetaClass(type):
  1056. def __new__(cls, name, parents, attrs):
  1057. attrs['a'] = 'abcde'
  1058. return type.__new__(cls, name, parents, attrs)
  1059. ```
  1060. ### Metaclass Attribute
  1061. **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.**
  1062. ```python
  1063. class MyClass(metaclass=MyMetaClass):
  1064. def __init__(self):
  1065. self.b = 12345
  1066. ```
  1067. Operator
  1068. --------
  1069. ```python
  1070. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  1071. eq, ne, lt, le, gt, ge, \
  1072. not_, and_, or_, \
  1073. itemgetter, attrgetter, methodcaller
  1074. ```
  1075. ```python
  1076. import operator as op
  1077. product_of_elems = functools.reduce(op.mul, <list>)
  1078. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1079. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1080. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1081. last_el = op.methodcaller('pop')(<list>)
  1082. ```
  1083. Eval
  1084. ----
  1085. ### Basic
  1086. ```python
  1087. >>> from ast import literal_eval
  1088. >>> literal_eval('1 + 2')
  1089. 3
  1090. >>> literal_eval('[1, 2, 3]')
  1091. [1, 2, 3]
  1092. >>> ast.literal_eval('abs(1)')
  1093. ValueError: malformed node or string
  1094. ```
  1095. ### Using Abstract Syntax Trees
  1096. ```python
  1097. import ast
  1098. from ast import Num, BinOp, UnaryOp
  1099. import operator as op
  1100. legal_operators = {ast.Add: op.add,
  1101. ast.Sub: op.sub,
  1102. ast.Mult: op.mul,
  1103. ast.Div: op.truediv,
  1104. ast.Pow: op.pow,
  1105. ast.BitXor: op.xor,
  1106. ast.USub: op.neg}
  1107. def evaluate(expression):
  1108. root = ast.parse(expression, mode='eval')
  1109. return eval_node(root.body)
  1110. def eval_node(node):
  1111. node_type = type(node)
  1112. if node_type == Num:
  1113. return node.n
  1114. if node_type not in [BinOp, UnaryOp]:
  1115. raise TypeError(node)
  1116. operator_type = type(node.op)
  1117. if operator_type not in legal_operators:
  1118. raise TypeError(f'Illegal operator {node.op}')
  1119. operator = legal_operators[operator_type]
  1120. if node_type == BinOp:
  1121. left, right = eval_node(node.left), eval_node(node.right)
  1122. return operator(left, right)
  1123. elif node_type == UnaryOp:
  1124. operand = eval_node(node.operand)
  1125. return operator(operand)
  1126. ```
  1127. ```python
  1128. >>> evaluate('2 ^ 6')
  1129. 4
  1130. >>> evaluate('2 ** 6')
  1131. 64
  1132. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1133. -5.0
  1134. ```
  1135. Coroutine
  1136. ---------
  1137. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1138. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1139. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1140. ### Helper Decorator
  1141. * **All coroutines must be "primed" by first calling next().**
  1142. * **Remembering to call next() is easy to forget.**
  1143. * **Solved by wrapping coroutines with a decorator:**
  1144. ```python
  1145. def coroutine(func):
  1146. def out(*args, **kwargs):
  1147. cr = func(*args, **kwargs)
  1148. next(cr)
  1149. return cr
  1150. return out
  1151. ```
  1152. ### Pipeline Example
  1153. ```python
  1154. def reader(target):
  1155. for i in range(10):
  1156. target.send(i)
  1157. target.close()
  1158. @coroutine
  1159. def adder(target):
  1160. while True:
  1161. item = (yield)
  1162. target.send(item + 100)
  1163. @coroutine
  1164. def printer():
  1165. while True:
  1166. item = (yield)
  1167. print(item)
  1168. reader(adder(printer())) # 100, 101, ..., 109
  1169. ```
  1170. <br><br>
  1171. Libraries
  1172. =========
  1173. Argparse
  1174. --------
  1175. ```python
  1176. from argparse import ArgumentParser
  1177. parser = ArgumentParser(description='calculate X to the power of Y')
  1178. group = parser.add_mutually_exclusive_group()
  1179. group.add_argument('-v', '--verbose', action='store_true')
  1180. group.add_argument('-q', '--quiet', action='store_true')
  1181. parser.add_argument('x', type=int, help='the base')
  1182. parser.add_argument('y', type=int, help='the exponent')
  1183. args = parser.parse_args()
  1184. answer = args.x ** args.y
  1185. if args.quiet:
  1186. print(answer)
  1187. elif args.verbose:
  1188. print(f'{args.x} to the power {args.y} equals {answer}')
  1189. else:
  1190. print(f'{args.x}^{args.y} == {answer}')
  1191. ```
  1192. ### Usage
  1193. ```text
  1194. $ python3 prog.py --help
  1195. usage: test2.py [-h] [-v | -q] x y
  1196. calculate X to the power of Y
  1197. positional arguments:
  1198. x the base
  1199. y the exponent
  1200. optional arguments:
  1201. -h, --help show this help message and exit
  1202. -v, --verbose
  1203. -q, --quiet
  1204. ```
  1205. Progress Bar
  1206. ------------
  1207. ```python
  1208. # $ pip3 install tqdm
  1209. from tqdm import tqdm
  1210. from time import sleep
  1211. for i in tqdm([1, 2, 3]):
  1212. sleep(0.2)
  1213. for i in tqdm(range(100)):
  1214. sleep(0.02)
  1215. ```
  1216. Table
  1217. -----
  1218. #### Prints CSV file as ASCII table:
  1219. ```python
  1220. # $ pip3 install tabulate
  1221. from csv import reader
  1222. from tabulate import tabulate
  1223. with open(<filename>, encoding='utf-8', newline='') as csv_file:
  1224. reader = reader(csv_file, delimiter=';')
  1225. headers = [a.title() for a in next(reader)]
  1226. print(tabulate(reader, headers))
  1227. ```
  1228. Curses
  1229. ------
  1230. ```python
  1231. # $ pip3 install curses
  1232. from curses import wrapper
  1233. def main():
  1234. wrapper(draw)
  1235. def draw(screen):
  1236. screen.clear()
  1237. screen.addstr(0, 0, 'Press ESC to quit.')
  1238. while screen.getch() != 27:
  1239. pass
  1240. def get_border(screen):
  1241. from collections import namedtuple
  1242. P = namedtuple('P', 'x y')
  1243. height, width = screen.getmaxyx()
  1244. return P(width - 1, height - 1)
  1245. ```
  1246. Plot
  1247. ----
  1248. ```python
  1249. # $ pip3 install matplotlib
  1250. from matplotlib import pyplot
  1251. pyplot.plot(<data_1> [, <data_2>, ...])
  1252. pyplot.savefig(<filename>, transparent=True)
  1253. pyplot.show()
  1254. ```
  1255. Image
  1256. -----
  1257. #### Creates PNG image of greyscale gradient:
  1258. ```python
  1259. # $ pip3 install pillow
  1260. from PIL import Image
  1261. width, height = 100, 100
  1262. img = Image.new('L', (width, height), 'white')
  1263. img.putdata([255 * a/(width*height) for a in range(width*height)])
  1264. img.save('out.png')
  1265. ```
  1266. ### Modes
  1267. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1268. * `'L'` - 8-bit pixels, greyscale.
  1269. * `'RGB'` - 3x8-bit pixels, true color.
  1270. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1271. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1272. Audio
  1273. -----
  1274. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1275. ```python
  1276. import wave, struct
  1277. samples = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1278. wf = wave.open(<filename>, 'wb')
  1279. wf.setnchannels(1)
  1280. wf.setsampwidth(4)
  1281. wf.setframerate(44100)
  1282. wf.writeframes(b''.join(samples))
  1283. wf.close()
  1284. ```
  1285. Url
  1286. ---
  1287. ```python
  1288. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1289. ```
  1290. ### Encode
  1291. ```python
  1292. >>> quote("Can't be in URL!")
  1293. 'Can%27t%20be%20in%20URL%21'
  1294. >>> quote_plus("Can't be in URL!")
  1295. 'Can%27t+be+in+URL%21'
  1296. ```
  1297. ### Decode
  1298. ```python
  1299. >>> unquote('Can%27t+be+in+URL%21')
  1300. "Can't+be+in+URL!"
  1301. >>> unquote_plus('Can%27t+be+in+URL%21')
  1302. "Can't be in URL!"
  1303. ```
  1304. Scraping
  1305. --------
  1306. ```python
  1307. # $ pip3 install requests beautifulsoup4
  1308. >>> import requests
  1309. >>> from bs4 import BeautifulSoup
  1310. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1311. >>> page = requests.get(url)
  1312. >>> document = BeautifulSoup(page.text, 'html.parser')
  1313. >>> table = document.find('table', class_='infobox vevent')
  1314. >>> rows = table.find_all('tr')
  1315. >>> link = rows[11].find('a')['href']
  1316. 'https://www.python.org/'
  1317. >>> latest_v = rows[6].find('div').text.split()[0]
  1318. '3.7.2'
  1319. ```
  1320. Web
  1321. ---
  1322. ```python
  1323. # $ pip3 install bottle
  1324. from bottle import run, route, post, template, request, response
  1325. import json
  1326. ```
  1327. ### Run
  1328. ```python
  1329. run(host='localhost', port=8080)
  1330. run(host='0.0.0.0', port=80, server='cherrypy')
  1331. ```
  1332. ### Static Request
  1333. ```python
  1334. @route('/img/<image>')
  1335. def send_image(image):
  1336. return static_file(image, 'images/', mimetype='image/png')
  1337. ```
  1338. ### Dynamic Request
  1339. ```python
  1340. @route('/<sport>')
  1341. def send_page(sport):
  1342. return template('<h1>{{title}}</h1>', title=sport)
  1343. ```
  1344. ### REST Request
  1345. ```python
  1346. @post('/odds/<sport>')
  1347. def odds_handler(sport):
  1348. team = request.forms.get('team')
  1349. home_odds, away_odds = 2.44, 3.29
  1350. response.headers['Content-Type'] = 'application/json'
  1351. response.headers['Cache-Control'] = 'no-cache'
  1352. return json.dumps([team, home_odds, away_odds])
  1353. ```
  1354. #### Test:
  1355. ```python
  1356. # $ pip3 install requests
  1357. >>> import requests
  1358. >>> url = 'http://localhost:8080/odds/football'
  1359. >>> r = requests.post(url, data={'team': 'arsenal f.c.'})
  1360. >>> r.json()
  1361. ['arsenal f.c.', 2.44, 3.29]
  1362. ```
  1363. Profile
  1364. -------
  1365. ### Basic
  1366. ```python
  1367. from time import time
  1368. start_time = time() # Seconds since Epoch.
  1369. ...
  1370. duration = time() - start_time
  1371. ```
  1372. ### High Performance
  1373. ```python
  1374. from time import perf_counter as pc
  1375. start_time = pc() # Seconds since restart.
  1376. ...
  1377. duration = pc() - start_time
  1378. ```
  1379. ### Timing a Snippet
  1380. ```python
  1381. from timeit import timeit
  1382. timeit('"-".join(str(a) for a in range(100))',
  1383. number=10000, globals=globals(), setup='pass')
  1384. ```
  1385. ### Line Profiler
  1386. ```python
  1387. # $ pip3 install line_profiler
  1388. @profile
  1389. def main():
  1390. a = [*range(10000)]
  1391. b = {*range(10000)}
  1392. main()
  1393. ```
  1394. #### Usage:
  1395. ```text
  1396. $ kernprof -lv test.py
  1397. Line # Hits Time Per Hit % Time Line Contents
  1398. ==============================================================
  1399. 1 @profile
  1400. 2 def main():
  1401. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1402. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1403. ```
  1404. ### Call Graph
  1405. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1406. ```python
  1407. # $ pip3 install pycallgraph
  1408. from pycallgraph import output, PyCallGraph
  1409. from datetime import datetime
  1410. graph = output.GraphvizOutput()
  1411. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1412. graph.output_file = f'profile-{time_str}.png'
  1413. with PyCallGraph(output=graph):
  1414. <code_to_be_profiled>
  1415. ```
  1416. NumPy
  1417. -----
  1418. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1419. ```python
  1420. # $ pip3 install numpy
  1421. import numpy as np
  1422. ```
  1423. ```python
  1424. <array> = np.array(<list>)
  1425. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1426. <array> = np.ones(<shape>)
  1427. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1428. ```
  1429. ```python
  1430. <array>.shape = <shape>
  1431. <view> = <array>.reshape(<shape>)
  1432. <view> = np.broadcast_to(<array>, <shape>)
  1433. ```
  1434. ```python
  1435. <array> = <array>.sum(<axis>)
  1436. indexes = <array>.argmin(<axis>)
  1437. ```
  1438. * **Shape is a tuple of dimension sizes.**
  1439. * **Axis is an index of dimension, that gets collapsed.**
  1440. ### Indexing
  1441. ```bash
  1442. <el> = <2d_array>[0, 0] # First element.
  1443. <1d_view> = <2d_array>[0] # First row.
  1444. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  1445. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  1446. ```
  1447. ```bash
  1448. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  1449. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  1450. ```
  1451. ```bash
  1452. <2d_bools> = <2d_array> > 0
  1453. <1d_array> = <2d_array>[<2d_bools>]
  1454. ```
  1455. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  1456. ### Broadcasting
  1457. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1458. ```python
  1459. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1460. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1461. ```
  1462. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1463. ```python
  1464. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1465. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1466. ```
  1467. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1468. ```python
  1469. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1470. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1471. ```
  1472. #### 3. If neither non-matching dimension has size 1, rise an error.
  1473. ### Example
  1474. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1475. ```python
  1476. >>> points = np.array([0.1, 0.6, 0.8])
  1477. [ 0.1, 0.6, 0.8]
  1478. >>> wrapped_points = points.reshape(3, 1)
  1479. [[ 0.1],
  1480. [ 0.6],
  1481. [ 0.8]]
  1482. >>> distances = wrapped_points - points
  1483. [[ 0. , -0.5, -0.7],
  1484. [ 0.5, 0. , -0.2],
  1485. [ 0.7, 0.2, 0. ]]
  1486. >>> distances = np.abs(distances)
  1487. [[ 0. , 0.5, 0.7],
  1488. [ 0.5, 0. , 0.2],
  1489. [ 0.7, 0.2, 0. ]]
  1490. >>> i = np.arange(3)
  1491. [0, 1, 2]
  1492. >>> distances[i, i] = np.inf
  1493. [[ inf, 0.5, 0.7],
  1494. [ 0.5, inf, 0.2],
  1495. [ 0.7, 0.2, inf]]
  1496. >>> distances.argmin(1)
  1497. [1, 2, 1]
  1498. ```
  1499. Basic Script Template
  1500. ---------------------
  1501. ```python
  1502. #!/usr/bin/env python3
  1503. #
  1504. # Usage: .py
  1505. #
  1506. from collections import namedtuple
  1507. from enum import Enum
  1508. import re
  1509. import sys
  1510. def main():
  1511. pass
  1512. ###
  1513. ## UTIL
  1514. #
  1515. def read_file(filename):
  1516. with open(filename, encoding='utf-8') as file:
  1517. return file.readlines()
  1518. if __name__ == '__main__':
  1519. main()
  1520. ```