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.

1830 lines
38 KiB

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