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.

1881 lines
41 KiB

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