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.

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