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.

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