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.

1795 lines
38 KiB

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