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.

1891 lines
41 KiB

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