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.

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