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.

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