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.

1927 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
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. ```
  815. ```python
  816. <iter> = <Path>.glob('<pattern>') # Returns all matches.
  817. <Path> = <Path>.resolve() # Makes path absolute.
  818. <file> = <Path>.open() # Opens file.
  819. ```
  820. ```python
  821. <str> = str(<Path>) # Returns path as string.
  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. <tuple> = <Path>.parts # All components as strings.
  827. ```
  828. JSON
  829. ----
  830. ```python
  831. import json
  832. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  833. <object> = json.loads(<str>)
  834. ```
  835. #### To preserve order:
  836. ```python
  837. from collections import OrderedDict
  838. <object> = json.loads(<str>, object_pairs_hook=OrderedDict)
  839. ```
  840. ### Read File
  841. ```python
  842. def read_json_file(filename):
  843. with open(filename, encoding='utf-8') as file:
  844. return json.load(file)
  845. ```
  846. ### Write to File
  847. ```python
  848. def write_to_json_file(filename, an_object):
  849. with open(filename, 'w', encoding='utf-8') as file:
  850. json.dump(an_object, file, ensure_ascii=False, indent=2)
  851. ```
  852. Pickle
  853. ------
  854. ```python
  855. import pickle
  856. <bytes> = pickle.dumps(<object>)
  857. <object> = pickle.loads(<bytes>)
  858. ```
  859. ### Read Object from File
  860. ```python
  861. def read_pickle_file(filename):
  862. with open(filename, 'rb') as file:
  863. return pickle.load(file)
  864. ```
  865. ### Write Object to File
  866. ```python
  867. def write_to_pickle_file(filename, an_object):
  868. with open(filename, 'wb') as file:
  869. pickle.dump(an_object, file)
  870. ```
  871. SQLite
  872. ------
  873. ```python
  874. import sqlite3
  875. db = sqlite3.connect(<filename>)
  876. ...
  877. db.close()
  878. ```
  879. ### Read
  880. ```python
  881. cursor = db.execute(<query>)
  882. if cursor:
  883. <tuple> = cursor.fetchone() # First row.
  884. <list> = cursor.fetchall() # Remaining rows.
  885. ```
  886. ### Write
  887. ```python
  888. db.execute(<query>)
  889. db.commit()
  890. ```
  891. Bytes
  892. -----
  893. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  894. ```python
  895. <bytes> = b'<str>'
  896. <int> = <bytes>[<index>]
  897. <bytes> = <bytes>[<slice>]
  898. <bytes> = b''.join(<coll_of_bytes>)
  899. ```
  900. ### Encode
  901. ```python
  902. <bytes> = <str>.encode(encoding='utf-8')
  903. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  904. <bytes> = bytes.fromhex(<hex>)
  905. ```
  906. ### Decode
  907. ```python
  908. <str> = <bytes>.decode('utf-8')
  909. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  910. <hex> = <bytes>.hex()
  911. ```
  912. ### Read Bytes from File
  913. ```python
  914. def read_bytes(filename):
  915. with open(filename, 'rb') as file:
  916. return file.read()
  917. ```
  918. ### Write Bytes to File
  919. ```python
  920. def write_bytes(filename, bytes_obj):
  921. with open(filename, 'wb') as file:
  922. file.write(bytes_obj)
  923. ```
  924. Struct
  925. ------
  926. * **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.**
  927. * **Machine’s native type sizes and byte order are used by default.**
  928. ```python
  929. from struct import pack, unpack, calcsize
  930. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  931. <tuple> = unpack('<format>', <bytes>)
  932. ```
  933. ### Example
  934. ```python
  935. >>> pack('>hhl', 1, 2, 3)
  936. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  937. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  938. (1, 2, 3)
  939. >>> calcsize('>hhl')
  940. 8
  941. ```
  942. ### Format
  943. #### For standard sizes start format string with:
  944. * **`'='` - native byte order**
  945. * **`'<'` - little-endian**
  946. * **`'>'` - big-endian**
  947. #### Use capital letter for unsigned type. Standard size in brackets:
  948. * **`'x'` - pad byte**
  949. * **`'c'` - char (1)**
  950. * **`'h'` - short (2)**
  951. * **`'i'` - int (4)**
  952. * **`'l'` - long (4)**
  953. * **`'q'` - long long (8)**
  954. * **`'f'` - float (4)**
  955. * **`'d'` - double (8)**
  956. Array
  957. -----
  958. **List that can only hold elements of predefined type. Available types are listed above.**
  959. ```python
  960. from array import array
  961. <array> = array(<typecode> [, <collection>])
  962. ```
  963. Memory View
  964. -----------
  965. **Used for accessing the internal data of an object that supports the buffer protocol.**
  966. ```python
  967. <memoryview> = memoryview(<bytes> / <bytearray> / <array>)
  968. <memoryview>.release()
  969. ```
  970. Deque
  971. -----
  972. **A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.**
  973. ```python
  974. from collections import deque
  975. <deque> = deque(<collection>, maxlen=None)
  976. ```
  977. ```python
  978. <deque>.appendleft(<el>)
  979. <deque>.extendleft(<collection>) # Collection gets reversed.
  980. <el> = <deque>.popleft()
  981. <deque>.rotate(n=1) # Rotates elements to the right.
  982. ```
  983. Threading
  984. ---------
  985. ```python
  986. from threading import Thread, RLock
  987. ```
  988. ### Thread
  989. ```python
  990. thread = Thread(target=<function>, args=(<first_arg>, ))
  991. thread.start()
  992. ...
  993. thread.join()
  994. ```
  995. ### Lock
  996. ```python
  997. lock = RLock()
  998. lock.acquire()
  999. ...
  1000. lock.release()
  1001. ```
  1002. Hashlib
  1003. -------
  1004. ```python
  1005. >>> import hashlib
  1006. >>> hashlib.md5(<str>.encode()).hexdigest()
  1007. '33d0eba106da4d3ebca17fcd3f4c3d77'
  1008. ```
  1009. Itertools
  1010. ---------
  1011. * **Every function returns an iterator and can accept any collection and/or iterator.**
  1012. * **If you want to print the iterator, you need to pass it to the list() function!**
  1013. ```python
  1014. from itertools import *
  1015. ```
  1016. ### Combinatoric iterators
  1017. ```python
  1018. >>> combinations('abc', 2)
  1019. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  1020. >>> combinations_with_replacement('abc', 2)
  1021. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  1022. ('b', 'b'), ('b', 'c'),
  1023. ('c', 'c')]
  1024. >>> permutations('abc', 2)
  1025. [('a', 'b'), ('a', 'c'),
  1026. ('b', 'a'), ('b', 'c'),
  1027. ('c', 'a'), ('c', 'b')]
  1028. >>> product('ab', [1, 2])
  1029. [('a', 1), ('a', 2),
  1030. ('b', 1), ('b', 2)]
  1031. >>> product([0, 1], repeat=3)
  1032. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  1033. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  1034. ```
  1035. ### Infinite iterators
  1036. ```python
  1037. >>> i = count(5, 2)
  1038. >>> next(i), next(i), next(i)
  1039. (5, 7, 9)
  1040. >>> a = cycle('abc')
  1041. >>> [next(a) for _ in range(10)]
  1042. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  1043. >>> repeat(10, 3)
  1044. [10, 10, 10]
  1045. ```
  1046. ### Iterators
  1047. ```python
  1048. >>> chain([1, 2], range(3, 5))
  1049. [1, 2, 3, 4]
  1050. >>> compress('abc', [True, 0, 1])
  1051. ['a', 'c']
  1052. >>> # islice(<collection>, from_inclusive, to_exclusive)
  1053. >>> islice([1, 2, 3], 1, None)
  1054. [2, 3]
  1055. >>> people = [{'id': 1, 'name': 'Bob'},
  1056. {'id': 2, 'name': 'Bob'},
  1057. {'id': 3, 'name': 'Peter'}]
  1058. >>> groups = groupby(people, key=lambda a: a['name'])
  1059. >>> {name: list(group) for name, group in groups}
  1060. {'Bob': [{'id': 1, 'name': 'Bob'},
  1061. {'id': 2, 'name': 'Bob'}],
  1062. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  1063. ```
  1064. Introspection and Metaprograming
  1065. --------------------------------
  1066. **Inspecting code at runtime and code that generates code. You can:**
  1067. * **Look at the attributes**
  1068. * **Set new attributes**
  1069. * **Create functions dynamically**
  1070. * **Traverse the parent classes**
  1071. * **Change values in the class**
  1072. ### Variables
  1073. ```python
  1074. <list> = dir() # Names of in-scope variables.
  1075. <dict> = locals() # Dict of local variables. Also vars().
  1076. <dict> = globals() # Dict of global variables.
  1077. ```
  1078. ### Attributes
  1079. ```python
  1080. class Z:
  1081. def __init__(self):
  1082. self.a = 'abcde'
  1083. self.b = 12345
  1084. ```
  1085. ```python
  1086. >>> z = Z()
  1087. >>> vars(z)
  1088. {'a': 'abcde', 'b': 12345}
  1089. >>> getattr(z, 'a')
  1090. 'abcde'
  1091. >>> hasattr(z, 'c')
  1092. False
  1093. >>> setattr(z, 'c', 10)
  1094. ```
  1095. ### Parameters
  1096. ```python
  1097. from inspect import signature
  1098. sig = signature(<function>)
  1099. no_of_params = len(sig.parameters)
  1100. param_names = list(sig.parameters.keys())
  1101. ```
  1102. ### Type
  1103. **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!).**
  1104. ```python
  1105. type(<class_name>, <parents_tuple>, <attributes_dict>)
  1106. ```
  1107. ```python
  1108. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1109. >>> z = Z()
  1110. ```
  1111. ### Meta Class
  1112. **Class that creates class.**
  1113. ```python
  1114. def my_meta_class(name, parents, attrs):
  1115. attrs['a'] = 'abcde'
  1116. return type(name, parents, attrs)
  1117. ```
  1118. #### Or:
  1119. ```python
  1120. class MyMetaClass(type):
  1121. def __new__(cls, name, parents, attrs):
  1122. attrs['a'] = 'abcde'
  1123. return type.__new__(cls, name, parents, attrs)
  1124. ```
  1125. ### Metaclass Attribute
  1126. **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.**
  1127. ```python
  1128. class MyClass(metaclass=MyMetaClass):
  1129. def __init__(self):
  1130. self.b = 12345
  1131. ```
  1132. Operator
  1133. --------
  1134. ```python
  1135. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  1136. eq, ne, lt, le, gt, ge, \
  1137. not_, and_, or_, \
  1138. itemgetter, attrgetter, methodcaller
  1139. ```
  1140. ```python
  1141. import operator as op
  1142. product_of_elems = functools.reduce(op.mul, <list>)
  1143. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1144. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1145. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1146. last_el = op.methodcaller('pop')(<list>)
  1147. ```
  1148. Eval
  1149. ----
  1150. ### Basic
  1151. ```python
  1152. >>> from ast import literal_eval
  1153. >>> literal_eval('1 + 2')
  1154. 3
  1155. >>> literal_eval('[1, 2, 3]')
  1156. [1, 2, 3]
  1157. >>> ast.literal_eval('abs(1)')
  1158. ValueError: malformed node or string
  1159. ```
  1160. ### Using Abstract Syntax Trees
  1161. ```python
  1162. import ast
  1163. from ast import Num, BinOp, UnaryOp
  1164. import operator as op
  1165. LEGAL_OPERATORS = {ast.Add: op.add,
  1166. ast.Sub: op.sub,
  1167. ast.Mult: op.mul,
  1168. ast.Div: op.truediv,
  1169. ast.Pow: op.pow,
  1170. ast.BitXor: op.xor,
  1171. ast.USub: op.neg}
  1172. def evaluate(expression):
  1173. root = ast.parse(expression, mode='eval')
  1174. return eval_node(root.body)
  1175. def eval_node(node):
  1176. node_type = type(node)
  1177. if node_type == Num:
  1178. return node.n
  1179. if node_type not in [BinOp, UnaryOp]:
  1180. raise TypeError(node)
  1181. operator_type = type(node.op)
  1182. if operator_type not in LEGAL_OPERATORS:
  1183. raise TypeError(f'Illegal operator {node.op}')
  1184. operator = LEGAL_OPERATORS[operator_type]
  1185. if node_type == BinOp:
  1186. left, right = eval_node(node.left), eval_node(node.right)
  1187. return operator(left, right)
  1188. elif node_type == UnaryOp:
  1189. operand = eval_node(node.operand)
  1190. return operator(operand)
  1191. ```
  1192. ```python
  1193. >>> evaluate('2 ^ 6')
  1194. 4
  1195. >>> evaluate('2 ** 6')
  1196. 64
  1197. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1198. -5.0
  1199. ```
  1200. Coroutine
  1201. ---------
  1202. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1203. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1204. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1205. ### Helper Decorator
  1206. * **All coroutines must be "primed" by first calling next().**
  1207. * **Remembering to call next() is easy to forget.**
  1208. * **Solved by wrapping coroutines with a decorator:**
  1209. ```python
  1210. def coroutine(func):
  1211. def out(*args, **kwargs):
  1212. cr = func(*args, **kwargs)
  1213. next(cr)
  1214. return cr
  1215. return out
  1216. ```
  1217. ### Pipeline Example
  1218. ```python
  1219. def reader(target):
  1220. for i in range(10):
  1221. target.send(i)
  1222. target.close()
  1223. @coroutine
  1224. def adder(target):
  1225. while True:
  1226. item = (yield)
  1227. target.send(item + 100)
  1228. @coroutine
  1229. def printer():
  1230. while True:
  1231. item = (yield)
  1232. print(item)
  1233. reader(adder(printer())) # 100, 101, ..., 109
  1234. ```
  1235. <br><br>
  1236. Libraries
  1237. =========
  1238. Progress Bar
  1239. ------------
  1240. ```python
  1241. # $ pip3 install tqdm
  1242. from tqdm import tqdm
  1243. from time import sleep
  1244. for i in tqdm([1, 2, 3]):
  1245. sleep(0.2)
  1246. for i in tqdm(range(100)):
  1247. sleep(0.02)
  1248. ```
  1249. Plot
  1250. ----
  1251. ```python
  1252. # $ pip3 install matplotlib
  1253. from matplotlib import pyplot
  1254. pyplot.plot(<data_1> [, <data_2>, ...])
  1255. pyplot.savefig(<filename>, transparent=True)
  1256. pyplot.show()
  1257. ```
  1258. Argparse
  1259. --------
  1260. ```python
  1261. from argparse import ArgumentParser
  1262. desc = 'calculate X to the power of Y'
  1263. parser = ArgumentParser(description=desc)
  1264. group = parser.add_mutually_exclusive_group()
  1265. group.add_argument('-v', '--verbose', action='store_true')
  1266. group.add_argument('-q', '--quiet', action='store_true')
  1267. parser.add_argument('x', type=int, help='the base')
  1268. parser.add_argument('y', type=int, help='the exponent')
  1269. args = parser.parse_args()
  1270. answer = args.x ** args.y
  1271. if args.quiet:
  1272. print(answer)
  1273. elif args.verbose:
  1274. print(f'{args.x} to the power {args.y} equals {answer}')
  1275. else:
  1276. print(f'{args.x}^{args.y} == {answer}')
  1277. ```
  1278. Table
  1279. -----
  1280. #### Prints CSV file as ASCII table:
  1281. ```python
  1282. # $ pip3 install tabulate
  1283. import csv
  1284. from tabulate import tabulate
  1285. with open(<filename>, encoding='utf-8') as file:
  1286. lines = csv.reader(file, delimiter=';')
  1287. headers = [header.title() for header in next(lines)]
  1288. table = tabulate(lines, headers)
  1289. print(table)
  1290. ```
  1291. Curses
  1292. ------
  1293. ```python
  1294. # $ pip3 install curses
  1295. from curses import wrapper
  1296. def main():
  1297. wrapper(draw)
  1298. def draw(screen):
  1299. screen.clear()
  1300. screen.addstr(0, 0, 'Press ESC to quit.')
  1301. while screen.getch() != 27:
  1302. pass
  1303. def get_border(screen):
  1304. from collections import namedtuple
  1305. P = namedtuple('P', 'x y')
  1306. height, width = screen.getmaxyx()
  1307. return P(width - 1, height - 1)
  1308. ```
  1309. Image
  1310. -----
  1311. #### Creates PNG image of greyscale gradient:
  1312. ```python
  1313. # $ pip3 install pillow
  1314. from PIL import Image
  1315. width = 100
  1316. height = 100
  1317. size = width * height
  1318. pixels = [255 * i/size for i in range(size)]
  1319. img = Image.new('L', (width, height), 'white')
  1320. img.putdata(pixels)
  1321. img.save('test.png')
  1322. ```
  1323. ### Modes
  1324. * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.**
  1325. * **`'L'` - 8-bit pixels, greyscale.**
  1326. * **`'RGB'` - 3x8-bit pixels, true color.**
  1327. * **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.**
  1328. * **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.**
  1329. Audio
  1330. -----
  1331. #### Saves a list of floats with values between -1 and 1 to a WAV file:
  1332. ```python
  1333. import wave, struct
  1334. samples = [struct.pack('<h', int(a * 30000)) for a in <list>]
  1335. wf = wave.open('test.wav', 'wb')
  1336. wf.setnchannels(1)
  1337. wf.setsampwidth(2)
  1338. wf.setframerate(44100)
  1339. wf.writeframes(b''.join(samples))
  1340. wf.close()
  1341. ```
  1342. ### Plays Popcorn
  1343. ```python
  1344. # pip3 install simpleaudio
  1345. import simpleaudio, math, struct
  1346. from itertools import chain, repeat
  1347. F = 44100
  1348. S1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,'
  1349. S2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'
  1350. get_pause = lambda seconds: repeat(0, int(seconds * F))
  1351. sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
  1352. get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
  1353. get_hz = lambda n: 8.176 * 2 ** (int(n) / 12)
  1354. parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125)
  1355. get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125)
  1356. samples_f = chain.from_iterable(get_note(n) for n in f'{S1}{S1}{S2}'.split(','))
  1357. samples_b = b''.join(struct.pack('<h', int(a * 30000)) for a in samples_f)
  1358. simpleaudio.play_buffer(samples_b, 1, 2, F)
  1359. ```
  1360. Url
  1361. ---
  1362. ```python
  1363. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1364. ```
  1365. ### Encode
  1366. ```python
  1367. >>> quote("Can't be in URL!")
  1368. 'Can%27t%20be%20in%20URL%21'
  1369. >>> quote_plus("Can't be in URL!")
  1370. 'Can%27t+be+in+URL%21'
  1371. ```
  1372. ### Decode
  1373. ```python
  1374. >>> unquote('Can%27t+be+in+URL%21')
  1375. "Can't+be+in+URL!"
  1376. >>> unquote_plus('Can%27t+be+in+URL%21')
  1377. "Can't be in URL!"
  1378. ```
  1379. Scraping
  1380. --------
  1381. ```python
  1382. # $ pip3 install requests beautifulsoup4
  1383. >>> import requests
  1384. >>> from bs4 import BeautifulSoup
  1385. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1386. >>> page = requests.get(url)
  1387. >>> doc = BeautifulSoup(page.text, 'html.parser')
  1388. >>> table = doc.find('table', class_='infobox vevent')
  1389. >>> rows = table.find_all('tr')
  1390. >>> link = rows[11].find('a')['href']
  1391. >>> ver = rows[6].find('div').text.split()[0]
  1392. >>> link, ver
  1393. ('https://www.python.org/', '3.7.2')
  1394. ```
  1395. Web
  1396. ---
  1397. ```python
  1398. # $ pip3 install bottle
  1399. from bottle import run, route, post, template, request, response
  1400. import json
  1401. ```
  1402. ### Run
  1403. ```python
  1404. run(host='localhost', port=8080)
  1405. run(host='0.0.0.0', port=80, server='cherrypy')
  1406. ```
  1407. ### Static Request
  1408. ```python
  1409. @route('/img/<image>')
  1410. def send_image(image):
  1411. return static_file(image, 'images/', mimetype='image/png')
  1412. ```
  1413. ### Dynamic Request
  1414. ```python
  1415. @route('/<sport>')
  1416. def send_page(sport):
  1417. return template('<h1>{{title}}</h1>', title=sport)
  1418. ```
  1419. ### REST Request
  1420. ```python
  1421. @post('/odds/<sport>')
  1422. def odds_handler(sport):
  1423. team = request.forms.get('team')
  1424. home_odds, away_odds = 2.44, 3.29
  1425. response.headers['Content-Type'] = 'application/json'
  1426. response.headers['Cache-Control'] = 'no-cache'
  1427. return json.dumps([team, home_odds, away_odds])
  1428. ```
  1429. #### Test:
  1430. ```python
  1431. # $ pip3 install requests
  1432. >>> import requests
  1433. >>> url = 'http://localhost:8080/odds/football'
  1434. >>> data = {'team': 'arsenal f.c.'}
  1435. >>> response = requests.post(url, data=data)
  1436. >>> response.json()
  1437. ['arsenal f.c.', 2.44, 3.29]
  1438. ```
  1439. Profile
  1440. -------
  1441. ### Basic
  1442. ```python
  1443. from time import time
  1444. start_time = time() # Seconds since Epoch.
  1445. ...
  1446. duration = time() - start_time
  1447. ```
  1448. ### High Performance
  1449. ```python
  1450. from time import perf_counter as pc
  1451. start_time = pc() # Seconds since restart.
  1452. ...
  1453. duration = pc() - start_time
  1454. ```
  1455. ### Timing a Snippet
  1456. ```python
  1457. from timeit import timeit
  1458. timeit('"-".join(str(a) for a in range(100))',
  1459. number=10000, globals=globals(), setup='pass')
  1460. ```
  1461. ### Line Profiler
  1462. ```python
  1463. # $ pip3 install line_profiler
  1464. @profile
  1465. def main():
  1466. a = [*range(10000)]
  1467. b = {*range(10000)}
  1468. main()
  1469. ```
  1470. #### Usage:
  1471. ```text
  1472. $ kernprof -lv test.py
  1473. Line # Hits Time Per Hit % Time Line Contents
  1474. ==============================================================
  1475. 1 @profile
  1476. 2 def main():
  1477. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1478. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1479. ```
  1480. ### Call Graph
  1481. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1482. ```python
  1483. # $ pip3 install pycallgraph
  1484. from pycallgraph import output, PyCallGraph
  1485. from datetime import datetime
  1486. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1487. filename = f'profile-{time_str}.png'
  1488. drawer = output.GraphvizOutput(output_file=filename)
  1489. with PyCallGraph(output=drawer):
  1490. <code_to_be_profiled>
  1491. ```
  1492. NumPy
  1493. -----
  1494. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1495. ```python
  1496. # $ pip3 install numpy
  1497. import numpy as np
  1498. ```
  1499. ```python
  1500. <array> = np.array(<list>)
  1501. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1502. <array> = np.ones(<shape>)
  1503. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1504. ```
  1505. ```python
  1506. <array>.shape = <shape>
  1507. <view> = <array>.reshape(<shape>)
  1508. <view> = np.broadcast_to(<array>, <shape>)
  1509. ```
  1510. ```python
  1511. <array> = <array>.sum(<axis>)
  1512. indexes = <array>.argmin(<axis>)
  1513. ```
  1514. * **Shape is a tuple of dimension sizes.**
  1515. * **Axis is an index of dimension that gets collapsed.**
  1516. ### Indexing
  1517. ```bash
  1518. <el> = <2d_array>[0, 0] # First element.
  1519. <1d_view> = <2d_array>[0] # First row.
  1520. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  1521. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  1522. ```
  1523. ```bash
  1524. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  1525. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  1526. ```
  1527. ```bash
  1528. <2d_bools> = <2d_array> > 0
  1529. <1d_array> = <2d_array>[<2d_bools>]
  1530. ```
  1531. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  1532. ### Broadcasting
  1533. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1534. ```python
  1535. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1536. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1537. ```
  1538. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1539. ```python
  1540. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1541. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1542. ```
  1543. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1544. ```python
  1545. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1546. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1547. ```
  1548. #### 3. If neither non-matching dimension has size 1, rise an error.
  1549. ### Example
  1550. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1551. ```python
  1552. >>> points = np.array([0.1, 0.6, 0.8])
  1553. [ 0.1, 0.6, 0.8]
  1554. >>> wrapped_points = points.reshape(3, 1)
  1555. [[ 0.1],
  1556. [ 0.6],
  1557. [ 0.8]]
  1558. >>> distances = wrapped_points - points
  1559. [[ 0. , -0.5, -0.7],
  1560. [ 0.5, 0. , -0.2],
  1561. [ 0.7, 0.2, 0. ]]
  1562. >>> distances = np.abs(distances)
  1563. [[ 0. , 0.5, 0.7],
  1564. [ 0.5, 0. , 0.2],
  1565. [ 0.7, 0.2, 0. ]]
  1566. >>> i = np.arange(3)
  1567. [0, 1, 2]
  1568. >>> distances[i, i] = np.inf
  1569. [[ inf, 0.5, 0.7],
  1570. [ 0.5, inf, 0.2],
  1571. [ 0.7, 0.2, inf]]
  1572. >>> distances.argmin(1)
  1573. [1, 2, 1]
  1574. ```
  1575. Basic Script Template
  1576. ---------------------
  1577. ```python
  1578. #!/usr/bin/env python3
  1579. #
  1580. # Usage: .py
  1581. #
  1582. from collections import namedtuple
  1583. from enum import Enum
  1584. import re
  1585. import sys
  1586. def main():
  1587. pass
  1588. ###
  1589. ## UTIL
  1590. #
  1591. def read_file(filename):
  1592. with open(filename, encoding='utf-8') as file:
  1593. return file.readlines()
  1594. if __name__ == '__main__':
  1595. main()
  1596. ```