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.

1876 lines
41 KiB

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