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.

2007 lines
44 KiB

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