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.

1923 lines
42 KiB

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