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.

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