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.

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