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.

1958 lines
43 KiB

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