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.

1932 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
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
5 years ago
6 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
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
5 years ago
6 years ago
5 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. list_of_chars = list(<str>)
  37. product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
  38. no_duplicates = list(dict.fromkeys(<list>))
  39. ```
  40. ```python
  41. index = <list>.index(<el>) # Returns first index of item.
  42. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  43. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  44. <list>.remove(<el>) # Removes first occurrence of item.
  45. <list>.clear() # Removes all items.
  46. ```
  47. Dictionary
  48. ----------
  49. ```python
  50. <view> = <dict>.keys()
  51. <view> = <dict>.values()
  52. <view> = <dict>.items()
  53. ```
  54. ```python
  55. value = <dict>.get(key, default) # Returns default if key does not exist.
  56. value = <dict>.setdefault(key, default) # Same, but also adds default to dict.
  57. <dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
  58. <dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
  59. ```
  60. ```python
  61. <dict>.update(<dict>) # Or: dict_a = {**dict_a, **dict_b}.
  62. <dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
  63. <dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
  64. <dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
  65. ```
  66. ```python
  67. value = <dict>.pop(key) # Removes item from dictionary.
  68. {k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
  69. ```
  70. ### Counter
  71. ```python
  72. >>> from collections import Counter
  73. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  74. >>> counter = Counter(colors)
  75. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  76. >>> counter.most_common()[0][0]
  77. 'blue'
  78. ```
  79. Set
  80. ---
  81. ```python
  82. <set> = set()
  83. ```
  84. ```python
  85. <set>.add(<el>)
  86. <set>.update(<collection>)
  87. <set> |= {<el>}
  88. <set> |= <set>
  89. ```
  90. ```python
  91. <set> = <set>.union(<coll.>) # Or: <set> | <set>
  92. <set> = <set>.intersection(<coll.>) # Or: <set> & <set>
  93. <set> = <set>.difference(<coll.>) # Or: <set> - <set>
  94. <set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
  95. <bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
  96. <bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
  97. ```
  98. ```python
  99. <set>.remove(<el>) # Throws error.
  100. <set>.discard(<el>) # Doesn't throw error.
  101. ```
  102. ### Frozenset
  103. #### Is hashable and can be used as a key in dictionary.
  104. ```python
  105. <frozenset> = frozenset(<collection>)
  106. ```
  107. Range
  108. -----
  109. ```python
  110. range(to_exclusive)
  111. range(from_inclusive, to_exclusive)
  112. range(from_inclusive, to_exclusive, step_size)
  113. range(from_inclusive, to_exclusive, -step_size)
  114. ```
  115. ```python
  116. from_inclusive = <range>.start
  117. to_exclusive = <range>.stop
  118. ```
  119. Enumerate
  120. ---------
  121. ```python
  122. for i, el in enumerate(<collection> [, i_start]):
  123. ...
  124. ```
  125. Named Tuple
  126. -----------
  127. ```python
  128. >>> Point = collections.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 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 first index of a substring.
  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 operators 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. **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:10}'
  266. ' 187'
  267. >>> '{p.height:10}'.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 = type(self).__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.a = 0
  627. def __call__(self):
  628. self.a += 1
  629. return self.a
  630. ```
  631. ### Copy
  632. ```python
  633. from copy import copy, deepcopy
  634. <object> = copy(<object>)
  635. <object> = deepcopy(<object>)
  636. ```
  637. Enum
  638. ----
  639. ```python
  640. from enum import Enum, auto
  641. class <enum_name>(Enum):
  642. <member_name_1> = <value_1>
  643. <member_name_2> = <value_2_a>, <value_2_b>
  644. <member_name_3> = auto()
  645. @classmethod
  646. def get_member_names(cls):
  647. return [a.name for a in cls.__members__.values()]
  648. ```
  649. ```python
  650. <member> = <enum>.<member_name>
  651. <member> = <enum>['<member_name>']
  652. <member> = <enum>(<value>)
  653. name = <member>.name
  654. value = <member>.value
  655. ```
  656. ```python
  657. list_of_members = list(<enum>)
  658. member_names = [a.name for a in <enum>]
  659. member_values = [a.value for a in <enum>]
  660. random_member = random.choice(list(<enum>))
  661. ```
  662. ### Inline
  663. ```python
  664. Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
  665. Cutlery = Enum('Cutlery', 'fork knife spoon')
  666. Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
  667. ```
  668. #### Functions can not be values, so they must be wrapped:
  669. ```python
  670. from functools import partial
  671. LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
  672. 'OR' : partial(lambda l, r: l or r)})
  673. ```
  674. Exceptions
  675. ----------
  676. ```python
  677. while True:
  678. try:
  679. x = int(input('Please enter a number: '))
  680. except ValueError:
  681. print('Oops! That was no valid number. Try again...')
  682. else:
  683. print('Thank you.')
  684. break
  685. ```
  686. #### Raising exception:
  687. ```python
  688. raise ValueError('A very specific message!')
  689. ```
  690. ### Finally
  691. ```python
  692. >>> try:
  693. ... raise KeyboardInterrupt
  694. ... finally:
  695. ... print('Goodbye, world!')
  696. Goodbye, world!
  697. Traceback (most recent call last):
  698. File "<stdin>", line 2, in <module>
  699. KeyboardInterrupt
  700. ```
  701. System
  702. ------
  703. ### Command Line Arguments
  704. ```python
  705. import sys
  706. script_name = sys.argv[0]
  707. arguments = sys.argv[1:]
  708. ```
  709. ### Print Function
  710. ```python
  711. print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  712. ```
  713. * **Use `'file=sys.stderr'` for errors.**
  714. #### Pretty print:
  715. ```python
  716. >>> from pprint import pprint
  717. >>> pprint(dir())
  718. ['__annotations__',
  719. '__builtins__',
  720. '__doc__', ...]
  721. ```
  722. ### Input Function
  723. * **Reads a line from user input or pipe if present.**
  724. * **The trailing newline gets stripped.**
  725. * **The prompt string is printed to standard output before reading input.**
  726. ```python
  727. <str> = input(prompt=None)
  728. ```
  729. #### Prints lines until EOF:
  730. ```python
  731. while True:
  732. try:
  733. print(input())
  734. except EOFError:
  735. break
  736. ```
  737. ### Open Function
  738. **Opens file and returns a corresponding file object.**
  739. ```python
  740. <file> = open('<path>', mode='r', encoding=None)
  741. ```
  742. #### Modes:
  743. * **`'r'` - Read (default).**
  744. * **`'w'` - Write (truncate).**
  745. * **`'x'` - Write or fail if the file already exists.**
  746. * **`'a'` - Append.**
  747. * **`'w+'` - Read and write (truncate).**
  748. * **`'r+'` - Read and write from the beginning.**
  749. * **`'a+'` - Read and write from the end.**
  750. * **`'t'` - Text mode (default).**
  751. * **`'b'` - Binary mode.**
  752. #### Seek:
  753. ```python
  754. <file>.seek(0) # Move to start of the file.
  755. <file>.seek(offset) # Move 'offset' chars/bytes from the start.
  756. <file>.seek(offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
  757. ```
  758. #### Read Text from File:
  759. ```python
  760. def read_file(filename):
  761. with open(filename, encoding='utf-8') as file:
  762. return file.readlines()
  763. ```
  764. #### Write Text to File:
  765. ```python
  766. def write_to_file(filename, text):
  767. with open(filename, 'w', encoding='utf-8') as file:
  768. file.write(text)
  769. ```
  770. ### Command Execution
  771. ```python
  772. import os
  773. <str> = os.popen(<command>).read()
  774. ```
  775. #### Or:
  776. ```python
  777. >>> import subprocess
  778. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  779. >>> a.stdout
  780. b'.\n..\nfile1.txt\nfile2.txt\n'
  781. >>> a.returncode
  782. 0
  783. ```
  784. ### Recursion Limit
  785. ```python
  786. >>> import sys
  787. >>> sys.getrecursionlimit()
  788. 1000
  789. >>> sys.setrecursionlimit(5000)
  790. ```
  791. ### Path
  792. ```python
  793. from os import path, listdir
  794. <bool> = path.exists('<path>')
  795. <bool> = path.isfile('<path>')
  796. <bool> = path.isdir('<path>')
  797. <list> = listdir('<path>')
  798. ```
  799. ```python
  800. >>> from glob import glob
  801. >>> glob('../*.gif')
  802. ['1.gif', 'card.gif']
  803. ```
  804. Pathlib
  805. -------
  806. **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.**
  807. ```python
  808. from pathlib import Path
  809. pwd = Path()
  810. <Path> = Path('<path>' [, '<path>', <Path>, ...])
  811. <Path> = <Path> / '<dir>' / '<file>'
  812. ```
  813. ```python
  814. <bool> = <Path>.exists()
  815. <bool> = <Path>.is_file()
  816. <bool> = <Path>.is_dir()
  817. <iter> = <Path>.iterdir()
  818. <iter> = <Path>.glob('<pattern>')
  819. ```
  820. ```python
  821. <str> = str(<Path>) # Returns path as string.
  822. <tup.> = <Path>.parts # Returns all components as strings.
  823. <Path> = <Path>.resolve() # Returns absolute path without symlinks.
  824. ```
  825. ```python
  826. <str> = <Path>.name # Final component.
  827. <str> = <Path>.stem # Final component without extension.
  828. <str> = <Path>.suffix # Final component's extension.
  829. <Path> = <Path>.parent # Path without final component.
  830. ```
  831. JSON
  832. ----
  833. ```python
  834. import json
  835. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  836. <object> = json.loads(<str>)
  837. ```
  838. #### To preserve order:
  839. ```python
  840. from collections import OrderedDict
  841. <object> = json.loads(<str>, object_pairs_hook=OrderedDict)
  842. ```
  843. ### Read File
  844. ```python
  845. def read_json_file(filename):
  846. with open(filename, encoding='utf-8') as file:
  847. return json.load(file)
  848. ```
  849. ### Write to File
  850. ```python
  851. def write_to_json_file(filename, an_object):
  852. with open(filename, 'w', encoding='utf-8') as file:
  853. json.dump(an_object, file, ensure_ascii=False, indent=2)
  854. ```
  855. Pickle
  856. ------
  857. ```python
  858. import pickle
  859. <bytes> = pickle.dumps(<object>)
  860. <object> = pickle.loads(<bytes>)
  861. ```
  862. ### Read Object from File
  863. ```python
  864. def read_pickle_file(filename):
  865. with open(filename, 'rb') as file:
  866. return pickle.load(file)
  867. ```
  868. ### Write Object to File
  869. ```python
  870. def write_to_pickle_file(filename, an_object):
  871. with open(filename, 'wb') as file:
  872. pickle.dump(an_object, file)
  873. ```
  874. SQLite
  875. ------
  876. ```python
  877. import sqlite3
  878. db = sqlite3.connect(<filename>)
  879. ...
  880. db.close()
  881. ```
  882. ### Read
  883. ```python
  884. cursor = db.execute(<query>)
  885. if cursor:
  886. <tuple> = cursor.fetchone() # First row.
  887. <list> = cursor.fetchall() # Remaining rows.
  888. ```
  889. ### Write
  890. ```python
  891. db.execute(<query>)
  892. db.commit()
  893. ```
  894. Bytes
  895. -----
  896. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  897. ```python
  898. <bytes> = b'<str>'
  899. <int> = <bytes>[<index>]
  900. <bytes> = <bytes>[<slice>]
  901. <bytes> = b''.join(<coll_of_bytes>)
  902. ```
  903. ### Encode
  904. ```python
  905. <bytes> = <str>.encode(encoding='utf-8')
  906. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  907. <bytes> = bytes.fromhex(<hex>)
  908. ```
  909. ### Decode
  910. ```python
  911. <str> = <bytes>.decode(encoding='utf-8')
  912. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  913. <hex> = <bytes>.hex()
  914. ```
  915. ### Read Bytes from File
  916. ```python
  917. def read_bytes(filename):
  918. with open(filename, 'rb') as file:
  919. return file.read()
  920. ```
  921. ### Write Bytes to File
  922. ```python
  923. def write_bytes(filename, bytes_obj):
  924. with open(filename, 'wb') as file:
  925. file.write(bytes_obj)
  926. ```
  927. Struct
  928. ------
  929. * **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.**
  930. * **Machine’s native type sizes and byte order are used by default.**
  931. ```python
  932. from struct import pack, unpack, calcsize
  933. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  934. <tuple> = unpack('<format>', <bytes>)
  935. ```
  936. ### Example
  937. ```python
  938. >>> pack('>hhl', 1, 2, 3)
  939. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  940. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  941. (1, 2, 3)
  942. >>> calcsize('>hhl')
  943. 8
  944. ```
  945. ### Format
  946. #### For standard sizes start format string with:
  947. * **`'='` - native byte order**
  948. * **`'<'` - little-endian**
  949. * **`'>'` - big-endian**
  950. #### Use capital letter for unsigned type. Standard size in brackets:
  951. * **`'x'` - pad byte**
  952. * **`'c'` - char (1)**
  953. * **`'h'` - short (2)**
  954. * **`'i'` - int (4)**
  955. * **`'l'` - long (4)**
  956. * **`'q'` - long long (8)**
  957. * **`'f'` - float (4)**
  958. * **`'d'` - double (8)**
  959. Array
  960. -----
  961. **List that can only hold elements of predefined type. Available types are listed above.**
  962. ```python
  963. from array import array
  964. <array> = array(<typecode> [, <collection>])
  965. ```
  966. Memory View
  967. -----------
  968. **Used for accessing the internal data of an object that supports the buffer protocol.**
  969. ```python
  970. <memoryview> = memoryview(<bytes> / <bytearray> / <array>)
  971. <memoryview>.release()
  972. ```
  973. Deque
  974. -----
  975. **A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.**
  976. ```python
  977. from collections import deque
  978. <deque> = deque(<collection>, maxlen=None)
  979. ```
  980. ```python
  981. <deque>.appendleft(<el>)
  982. <deque>.extendleft(<collection>) # Collection gets reversed.
  983. <el> = <deque>.popleft()
  984. <deque>.rotate(n=1) # Rotates elements to the right.
  985. ```
  986. Threading
  987. ---------
  988. ```python
  989. from threading import Thread, RLock
  990. ```
  991. ### Thread
  992. ```python
  993. thread = Thread(target=<function>, args=(<first_arg>, ))
  994. thread.start()
  995. ...
  996. thread.join()
  997. ```
  998. ### Lock
  999. ```python
  1000. lock = RLock()
  1001. lock.acquire()
  1002. ...
  1003. lock.release()
  1004. ```
  1005. Hashlib
  1006. -------
  1007. ```python
  1008. >>> import hashlib
  1009. >>> hashlib.md5(<str>.encode()).hexdigest()
  1010. '33d0eba106da4d3ebca17fcd3f4c3d77'
  1011. ```
  1012. Itertools
  1013. ---------
  1014. * **Every function returns an iterator and can accept any collection and/or iterator.**
  1015. * **If you want to print the iterator, you need to pass it to the list() function!**
  1016. ```python
  1017. from itertools import *
  1018. ```
  1019. ### Combinatoric iterators
  1020. ```python
  1021. >>> combinations('abc', 2)
  1022. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  1023. >>> combinations_with_replacement('abc', 2)
  1024. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  1025. ('b', 'b'), ('b', 'c'),
  1026. ('c', 'c')]
  1027. >>> permutations('abc', 2)
  1028. [('a', 'b'), ('a', 'c'),
  1029. ('b', 'a'), ('b', 'c'),
  1030. ('c', 'a'), ('c', 'b')]
  1031. >>> product('ab', '12')
  1032. [('a', '1'), ('a', '2'),
  1033. ('b', '1'), ('b', '2')]
  1034. >>> product([0, 1], repeat=3)
  1035. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  1036. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  1037. ```
  1038. ### Infinite iterators
  1039. ```python
  1040. >>> i = count(5, 2)
  1041. >>> next(i), next(i), next(i)
  1042. (5, 7, 9)
  1043. >>> a = cycle('abc')
  1044. >>> [next(a) for _ in range(10)]
  1045. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  1046. >>> repeat(10, 3)
  1047. [10, 10, 10]
  1048. ```
  1049. ### Iterators
  1050. ```python
  1051. >>> chain([1, 2], range(3, 5))
  1052. [1, 2, 3, 4]
  1053. >>> compress('abc', [True, 0, 1])
  1054. ['a', 'c']
  1055. >>> # islice(<collection>, from_inclusive, to_exclusive)
  1056. >>> islice([1, 2, 3], 1, None)
  1057. [2, 3]
  1058. >>> people = [{'id': 1, 'name': 'Bob'},
  1059. {'id': 2, 'name': 'Bob'},
  1060. {'id': 3, 'name': 'Peter'}]
  1061. >>> groups = groupby(people, key=lambda a: a['name'])
  1062. >>> {name: list(group) for name, group in groups}
  1063. {'Bob': [{'id': 1, 'name': 'Bob'},
  1064. {'id': 2, 'name': 'Bob'}],
  1065. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  1066. ```
  1067. Introspection and Metaprograming
  1068. --------------------------------
  1069. **Inspecting code at runtime and code that generates code. You can:**
  1070. * **Look at the attributes**
  1071. * **Set new attributes**
  1072. * **Create functions dynamically**
  1073. * **Traverse the parent classes**
  1074. * **Change values in the class**
  1075. ### Variables
  1076. ```python
  1077. <list> = dir() # Names of in-scope variables.
  1078. <dict> = locals() # Dict of local variables. Also vars().
  1079. <dict> = globals() # Dict of global variables.
  1080. ```
  1081. ### Attributes
  1082. ```python
  1083. class Z:
  1084. def __init__(self):
  1085. self.a = 'abcde'
  1086. self.b = 12345
  1087. ```
  1088. ```python
  1089. >>> z = Z()
  1090. >>> vars(z)
  1091. {'a': 'abcde', 'b': 12345}
  1092. >>> getattr(z, 'a')
  1093. 'abcde'
  1094. >>> hasattr(z, 'c')
  1095. False
  1096. >>> setattr(z, 'c', 10)
  1097. ```
  1098. ### Parameters
  1099. ```python
  1100. from inspect import signature
  1101. sig = signature(<function>)
  1102. no_of_params = len(sig.parameters)
  1103. param_names = list(sig.parameters.keys())
  1104. ```
  1105. ### Type
  1106. **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!).**
  1107. ```python
  1108. type(<class_name>, <parents_tuple>, <attributes_dict>)
  1109. ```
  1110. ```python
  1111. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1112. >>> z = Z()
  1113. ```
  1114. ### Meta Class
  1115. **Class that creates class.**
  1116. ```python
  1117. def my_meta_class(name, parents, attrs):
  1118. attrs['a'] = 'abcde'
  1119. return type(name, parents, attrs)
  1120. ```
  1121. #### Or:
  1122. ```python
  1123. class MyMetaClass(type):
  1124. def __new__(cls, name, parents, attrs):
  1125. attrs['a'] = 'abcde'
  1126. return type.__new__(cls, name, parents, attrs)
  1127. ```
  1128. ### Metaclass Attribute
  1129. **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.**
  1130. ```python
  1131. class MyClass(metaclass=MyMetaClass):
  1132. def __init__(self):
  1133. self.b = 12345
  1134. ```
  1135. Operator
  1136. --------
  1137. ```python
  1138. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  1139. eq, ne, lt, le, gt, ge, \
  1140. not_, and_, or_, \
  1141. itemgetter, attrgetter, methodcaller
  1142. ```
  1143. ```python
  1144. import operator as op
  1145. product_of_elems = functools.reduce(op.mul, <list>)
  1146. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1147. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1148. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1149. last_el = op.methodcaller('pop')(<list>)
  1150. ```
  1151. Eval
  1152. ----
  1153. ### Basic
  1154. ```python
  1155. >>> from ast import literal_eval
  1156. >>> literal_eval('1 + 2')
  1157. 3
  1158. >>> literal_eval('[1, 2, 3]')
  1159. [1, 2, 3]
  1160. >>> ast.literal_eval('abs(1)')
  1161. ValueError: malformed node or string
  1162. ```
  1163. ### Using Abstract Syntax Trees
  1164. ```python
  1165. import ast
  1166. from ast import Num, BinOp, UnaryOp
  1167. import operator as op
  1168. LEGAL_OPERATORS = {ast.Add: op.add,
  1169. ast.Sub: op.sub,
  1170. ast.Mult: op.mul,
  1171. ast.Div: op.truediv,
  1172. ast.Pow: op.pow,
  1173. ast.BitXor: op.xor,
  1174. ast.USub: op.neg}
  1175. def evaluate(expression):
  1176. root = ast.parse(expression, mode='eval')
  1177. return eval_node(root.body)
  1178. def eval_node(node):
  1179. node_type = type(node)
  1180. if node_type == Num:
  1181. return node.n
  1182. if node_type not in [BinOp, UnaryOp]:
  1183. raise TypeError(node)
  1184. operator_type = type(node.op)
  1185. if operator_type not in LEGAL_OPERATORS:
  1186. raise TypeError(f'Illegal operator {node.op}')
  1187. operator = LEGAL_OPERATORS[operator_type]
  1188. if node_type == BinOp:
  1189. left, right = eval_node(node.left), eval_node(node.right)
  1190. return operator(left, right)
  1191. elif node_type == UnaryOp:
  1192. operand = eval_node(node.operand)
  1193. return operator(operand)
  1194. ```
  1195. ```python
  1196. >>> evaluate('2 ^ 6')
  1197. 4
  1198. >>> evaluate('2 ** 6')
  1199. 64
  1200. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1201. -5.0
  1202. ```
  1203. Coroutine
  1204. ---------
  1205. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1206. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1207. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1208. ### Helper Decorator
  1209. * **All coroutines must be "primed" by first calling next().**
  1210. * **Remembering to call next() is easy to forget.**
  1211. * **Solved by wrapping coroutines with a decorator:**
  1212. ```python
  1213. def coroutine(func):
  1214. def out(*args, **kwargs):
  1215. cr = func(*args, **kwargs)
  1216. next(cr)
  1217. return cr
  1218. return out
  1219. ```
  1220. ### Pipeline Example
  1221. ```python
  1222. def reader(target):
  1223. for i in range(10):
  1224. target.send(i)
  1225. target.close()
  1226. @coroutine
  1227. def adder(target):
  1228. while True:
  1229. item = (yield)
  1230. target.send(item + 100)
  1231. @coroutine
  1232. def printer():
  1233. while True:
  1234. item = (yield)
  1235. print(item)
  1236. reader(adder(printer())) # 100, 101, ..., 109
  1237. ```
  1238. <br><br>
  1239. Libraries
  1240. =========
  1241. Progress Bar
  1242. ------------
  1243. ```python
  1244. # $ pip3 install tqdm
  1245. from tqdm import tqdm
  1246. from time import sleep
  1247. for i in tqdm([1, 2, 3]):
  1248. sleep(0.2)
  1249. for i in tqdm(range(100)):
  1250. sleep(0.02)
  1251. ```
  1252. Plot
  1253. ----
  1254. ```python
  1255. # $ pip3 install matplotlib
  1256. from matplotlib import pyplot
  1257. pyplot.plot(<data_1> [, <data_2>, ...])
  1258. pyplot.savefig(<filename>, transparent=True)
  1259. pyplot.show()
  1260. ```
  1261. Argparse
  1262. --------
  1263. ```python
  1264. from argparse import ArgumentParser
  1265. desc = 'calculate X to the power of Y'
  1266. parser = ArgumentParser(description=desc)
  1267. group = parser.add_mutually_exclusive_group()
  1268. group.add_argument('-v', '--verbose', action='store_true')
  1269. group.add_argument('-q', '--quiet', action='store_true')
  1270. parser.add_argument('x', type=int, help='the base')
  1271. parser.add_argument('y', type=int, help='the exponent')
  1272. args = parser.parse_args()
  1273. answer = args.x ** args.y
  1274. if args.quiet:
  1275. print(answer)
  1276. elif args.verbose:
  1277. print(f'{args.x} to the power {args.y} equals {answer}')
  1278. else:
  1279. print(f'{args.x}^{args.y} == {answer}')
  1280. ```
  1281. Table
  1282. -----
  1283. #### Prints CSV file as ASCII table:
  1284. ```python
  1285. # $ pip3 install tabulate
  1286. import csv
  1287. from tabulate import tabulate
  1288. with open(<filename>, encoding='utf-8') as file:
  1289. lines = csv.reader(file, delimiter=';')
  1290. headers = [header.title() for header in next(lines)]
  1291. table = tabulate(lines, headers)
  1292. print(table)
  1293. ```
  1294. Curses
  1295. ------
  1296. ```python
  1297. # $ pip3 install curses
  1298. from curses import wrapper
  1299. def main():
  1300. wrapper(draw)
  1301. def draw(screen):
  1302. screen.clear()
  1303. screen.addstr(0, 0, 'Press ESC to quit.')
  1304. while screen.getch() != 27:
  1305. pass
  1306. def get_border(screen):
  1307. from collections import namedtuple
  1308. P = namedtuple('P', 'x y')
  1309. height, width = screen.getmaxyx()
  1310. return P(width - 1, height - 1)
  1311. ```
  1312. Image
  1313. -----
  1314. #### Creates PNG image of greyscale gradient:
  1315. ```python
  1316. # $ pip3 install pillow
  1317. from PIL import Image
  1318. width = 100
  1319. height = 100
  1320. size = width * height
  1321. pixels = [255 * i/size for i in range(size)]
  1322. img = Image.new('L', (width, height), 'white')
  1323. img.putdata(pixels)
  1324. img.save('test.png')
  1325. ```
  1326. ### Modes
  1327. * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.**
  1328. * **`'L'` - 8-bit pixels, greyscale.**
  1329. * **`'RGB'` - 3x8-bit pixels, true color.**
  1330. * **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.**
  1331. * **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.**
  1332. Audio
  1333. -----
  1334. #### Saves a list of floats with values between -1 and 1 to a WAV file:
  1335. ```python
  1336. import wave, struct
  1337. samples = [struct.pack('<h', int(a * 30000)) for a in <list>]
  1338. wf = wave.open('test.wav', 'wb')
  1339. wf.setnchannels(1)
  1340. wf.setsampwidth(2)
  1341. wf.setframerate(44100)
  1342. wf.writeframes(b''.join(samples))
  1343. wf.close()
  1344. ```
  1345. ### Plays Popcorn
  1346. ```python
  1347. # pip3 install simpleaudio
  1348. import simpleaudio, math, struct
  1349. from itertools import chain, repeat
  1350. F = 44100
  1351. P1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,'
  1352. P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'
  1353. get_pause = lambda seconds: repeat(0, int(seconds * F))
  1354. sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
  1355. get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
  1356. get_hz = lambda n: 8.176 * 2 ** (int(n) / 12)
  1357. parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125)
  1358. get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125)
  1359. samples_f = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(','))
  1360. samples_b = b''.join(struct.pack('<h', int(a * 30000)) for a in samples_f)
  1361. simpleaudio.play_buffer(samples_b, 1, 2, F)
  1362. ```
  1363. Url
  1364. ---
  1365. ```python
  1366. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1367. ```
  1368. ### Encode
  1369. ```python
  1370. >>> quote("Can't be in URL!")
  1371. 'Can%27t%20be%20in%20URL%21'
  1372. >>> quote_plus("Can't be in URL!")
  1373. 'Can%27t+be+in+URL%21'
  1374. ```
  1375. ### Decode
  1376. ```python
  1377. >>> unquote('Can%27t+be+in+URL%21')
  1378. "Can't+be+in+URL!"
  1379. >>> unquote_plus('Can%27t+be+in+URL%21')
  1380. "Can't be in URL!"
  1381. ```
  1382. Scraping
  1383. --------
  1384. ```python
  1385. # $ pip3 install requests beautifulsoup4
  1386. >>> import requests
  1387. >>> from bs4 import BeautifulSoup
  1388. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1389. >>> page = requests.get(url)
  1390. >>> doc = BeautifulSoup(page.text, 'html.parser')
  1391. >>> table = doc.find('table', class_='infobox vevent')
  1392. >>> rows = table.find_all('tr')
  1393. >>> link = rows[11].find('a')['href']
  1394. >>> ver = rows[6].find('div').text.split()[0]
  1395. >>> link, ver
  1396. ('https://www.python.org/', '3.7.2')
  1397. ```
  1398. Web
  1399. ---
  1400. ```python
  1401. # $ pip3 install bottle
  1402. from bottle import run, route, post, template, request, response
  1403. import json
  1404. ```
  1405. ### Run
  1406. ```python
  1407. run(host='localhost', port=8080)
  1408. run(host='0.0.0.0', port=80, server='cherrypy')
  1409. ```
  1410. ### Static Request
  1411. ```python
  1412. @route('/img/<image>')
  1413. def send_image(image):
  1414. return static_file(image, 'images/', mimetype='image/png')
  1415. ```
  1416. ### Dynamic Request
  1417. ```python
  1418. @route('/<sport>')
  1419. def send_page(sport):
  1420. return template('<h1>{{title}}</h1>', title=sport)
  1421. ```
  1422. ### REST Request
  1423. ```python
  1424. @post('/odds/<sport>')
  1425. def odds_handler(sport):
  1426. team = request.forms.get('team')
  1427. home_odds, away_odds = 2.44, 3.29
  1428. response.headers['Content-Type'] = 'application/json'
  1429. response.headers['Cache-Control'] = 'no-cache'
  1430. return json.dumps([team, home_odds, away_odds])
  1431. ```
  1432. #### Test:
  1433. ```python
  1434. # $ pip3 install requests
  1435. >>> import requests
  1436. >>> url = 'http://localhost:8080/odds/football'
  1437. >>> data = {'team': 'arsenal f.c.'}
  1438. >>> response = requests.post(url, data=data)
  1439. >>> response.json()
  1440. ['arsenal f.c.', 2.44, 3.29]
  1441. ```
  1442. Profile
  1443. -------
  1444. ### Basic
  1445. ```python
  1446. from time import time
  1447. start_time = time() # Seconds since Epoch.
  1448. ...
  1449. duration = time() - start_time
  1450. ```
  1451. ### High Performance
  1452. ```python
  1453. from time import perf_counter as pc
  1454. start_time = pc() # Seconds since restart.
  1455. ...
  1456. duration = pc() - start_time
  1457. ```
  1458. ### Timing a Snippet
  1459. ```python
  1460. from timeit import timeit
  1461. timeit('"-".join(str(a) for a in range(100))',
  1462. number=10000, globals=globals(), setup='pass')
  1463. ```
  1464. ### Line Profiler
  1465. ```python
  1466. # $ pip3 install line_profiler
  1467. @profile
  1468. def main():
  1469. a = [*range(10000)]
  1470. b = {*range(10000)}
  1471. main()
  1472. ```
  1473. #### Usage:
  1474. ```text
  1475. $ kernprof -lv test.py
  1476. Line # Hits Time Per Hit % Time Line Contents
  1477. ==============================================================
  1478. 1 @profile
  1479. 2 def main():
  1480. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1481. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1482. ```
  1483. ### Call Graph
  1484. #### Generates a PNG image of a call graph with highlighted bottlenecks:
  1485. ```python
  1486. # $ pip3 install pycallgraph
  1487. from pycallgraph import output, PyCallGraph
  1488. from datetime import datetime
  1489. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1490. filename = f'profile-{time_str}.png'
  1491. drawer = output.GraphvizOutput(output_file=filename)
  1492. with PyCallGraph(output=drawer):
  1493. <code_to_be_profiled>
  1494. ```
  1495. NumPy
  1496. -----
  1497. **Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.**
  1498. ```python
  1499. # $ pip3 install numpy
  1500. import numpy as np
  1501. ```
  1502. ```python
  1503. <array> = np.array(<list>)
  1504. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1505. <array> = np.ones(<shape>)
  1506. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1507. ```
  1508. ```python
  1509. <array>.shape = <shape>
  1510. <view> = <array>.reshape(<shape>)
  1511. <view> = np.broadcast_to(<array>, <shape>)
  1512. ```
  1513. ```python
  1514. <array> = <array>.sum(<axis>)
  1515. indexes = <array>.argmin(<axis>)
  1516. ```
  1517. * **Shape is a tuple of dimension sizes.**
  1518. * **Axis is an index of dimension that gets collapsed.**
  1519. ### Indexing
  1520. ```bash
  1521. <el> = <2d_array>[0, 0] # First element.
  1522. <1d_view> = <2d_array>[0] # First row.
  1523. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  1524. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  1525. ```
  1526. ```bash
  1527. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  1528. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  1529. ```
  1530. ```bash
  1531. <2d_bools> = <2d_array> > 0
  1532. <1d_array> = <2d_array>[<2d_bools>]
  1533. ```
  1534. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  1535. ### Broadcasting
  1536. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1537. ```python
  1538. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1539. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1540. ```
  1541. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1542. ```python
  1543. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1544. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1545. ```
  1546. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1547. ```python
  1548. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1549. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1550. ```
  1551. #### 3. If neither non-matching dimension has size 1, rise an error.
  1552. ### Example
  1553. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1554. ```python
  1555. >>> points = np.array([0.1, 0.6, 0.8])
  1556. [ 0.1, 0.6, 0.8]
  1557. >>> wrapped_points = points.reshape(3, 1)
  1558. [[ 0.1],
  1559. [ 0.6],
  1560. [ 0.8]]
  1561. >>> distances = wrapped_points - points
  1562. [[ 0. , -0.5, -0.7],
  1563. [ 0.5, 0. , -0.2],
  1564. [ 0.7, 0.2, 0. ]]
  1565. >>> distances = np.abs(distances)
  1566. [[ 0. , 0.5, 0.7],
  1567. [ 0.5, 0. , 0.2],
  1568. [ 0.7, 0.2, 0. ]]
  1569. >>> i = np.arange(3)
  1570. [0, 1, 2]
  1571. >>> distances[i, i] = np.inf
  1572. [[ inf, 0.5, 0.7],
  1573. [ 0.5, inf, 0.2],
  1574. [ 0.7, 0.2, inf]]
  1575. >>> distances.argmin(1)
  1576. [1, 2, 1]
  1577. ```
  1578. Basic Script Template
  1579. ---------------------
  1580. ```python
  1581. #!/usr/bin/env python3
  1582. #
  1583. # Usage: .py
  1584. #
  1585. from collections import namedtuple
  1586. from enum import Enum
  1587. import re
  1588. import sys
  1589. def main():
  1590. pass
  1591. ###
  1592. ## UTIL
  1593. #
  1594. def read_file(filename):
  1595. with open(filename, encoding='utf-8') as file:
  1596. return file.readlines()
  1597. if __name__ == '__main__':
  1598. main()
  1599. ```