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.

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