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.

2047 lines
45 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
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
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
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
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
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. Command Line Arguments
  792. ----------------------
  793. ```python
  794. import sys
  795. script_name = sys.argv[0]
  796. arguments = sys.argv[1:]
  797. ```
  798. ### Argparse
  799. ```python
  800. from argparse import ArgumentParser, FileType
  801. p = ArgumentParser(description=<str>)
  802. p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag
  803. p.add_argument('-<short_name>', '--<name>', type=<type>) # Option
  804. p.add_argument('<name>', type=<type>, nargs=1) # Argument
  805. p.add_argument('<name>', type=<type>, nargs='+') # Arguments
  806. args = p.parse_args()
  807. value = args.<name>
  808. ```
  809. * **Use `'help=<str>'` for argument description.**
  810. * **Use `'type=FileType(<mode>)'` for files.**
  811. Open
  812. ----
  813. **Opens file and returns a corresponding file object.**
  814. ```python
  815. <file> = open('<path>', mode='r', encoding=None)
  816. ```
  817. ### Modes
  818. * **`'r'` - Read (default).**
  819. * **`'w'` - Write (truncate).**
  820. * **`'x'` - Write or fail if the file already exists.**
  821. * **`'a'` - Append.**
  822. * **`'w+'` - Read and write (truncate).**
  823. * **`'r+'` - Read and write from the start.**
  824. * **`'a+'` - Read and write from the end.**
  825. * **`'t'` - Text mode (default).**
  826. * **`'b'` - Binary mode.**
  827. ### Seek
  828. ```python
  829. <file>.seek(0) # Move to the start of the file.
  830. <file>.seek(offset) # Move 'offset' chars/bytes from the start.
  831. <file>.seek(offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
  832. ```
  833. ### Read Text from File
  834. ```python
  835. def read_file(filename):
  836. with open(filename, encoding='utf-8') as file:
  837. return file.readlines()
  838. ```
  839. ### Write Text to File
  840. ```python
  841. def write_to_file(filename, text):
  842. with open(filename, 'w', encoding='utf-8') as file:
  843. file.write(text)
  844. ```
  845. Path
  846. ----
  847. ```python
  848. from os import path, listdir
  849. <bool> = path.exists('<path>')
  850. <bool> = path.isfile('<path>')
  851. <bool> = path.isdir('<path>')
  852. <list> = listdir('<path>')
  853. ```
  854. ```python
  855. >>> from glob import glob
  856. >>> glob('../*.gif')
  857. ['1.gif', 'card.gif']
  858. ```
  859. ### Pathlib
  860. ```python
  861. from pathlib import Path
  862. cwd = Path()
  863. <Path> = Path('<path>' [, '<path>', <Path>, ...])
  864. <Path> = <Path> / '<dir>' / '<file>'
  865. ```
  866. ```python
  867. <bool> = <Path>.exists()
  868. <bool> = <Path>.is_file()
  869. <bool> = <Path>.is_dir()
  870. <iter> = <Path>.iterdir()
  871. <iter> = <Path>.glob('<pattern>')
  872. ```
  873. ```python
  874. <str> = str(<Path>) # Returns path as string.
  875. <tup.> = <Path>.parts # Returns all components as strings.
  876. <Path> = <Path>.resolve() # Returns absolute path without symlinks.
  877. ```
  878. ```python
  879. <str> = <Path>.name # Final component.
  880. <str> = <Path>.stem # Final component without extension.
  881. <str> = <Path>.suffix # Final component's extension.
  882. <Path> = <Path>.parent # Path without final component.
  883. ```
  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. <ints> = list(<bytes>)
  997. ```
  998. ### Encode
  999. ```python
  1000. <bytes> = <str>.encode(encoding='utf-8')
  1001. <bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
  1002. <bytes> = bytes.fromhex('<hex>')
  1003. ```
  1004. ### Decode
  1005. ```python
  1006. <str> = <bytes>.decode(encoding='utf-8')
  1007. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  1008. <hex> = <bytes>.hex()
  1009. ```
  1010. ### Read Bytes from File
  1011. ```python
  1012. def read_bytes(filename):
  1013. with open(filename, 'rb') as file:
  1014. return file.read()
  1015. ```
  1016. ### Write Bytes to File
  1017. ```python
  1018. def write_bytes(filename, bytes_obj):
  1019. with open(filename, 'wb') as file:
  1020. file.write(bytes_obj)
  1021. ```
  1022. Struct
  1023. ------
  1024. * **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.**
  1025. * **Machine’s native type sizes and byte order are used by default.**
  1026. ```python
  1027. from struct import pack, unpack, iter_unpack, calcsize
  1028. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  1029. <tuple> = unpack('<format>', <bytes>)
  1030. <iter> = iter_unpack('<format>', <bytes>)
  1031. ```
  1032. ### Example
  1033. ```python
  1034. >>> pack('>hhl', 1, 2, 3)
  1035. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  1036. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  1037. (1, 2, 3)
  1038. >>> calcsize('>hhl')
  1039. 8
  1040. ```
  1041. ### Format
  1042. #### For standard sizes start format string with:
  1043. * **`'='` - native byte order**
  1044. * **`'<'` - little-endian**
  1045. * **`'>'` - big-endian**
  1046. #### Use capital letter for unsigned type. Standard sizes are in brackets:
  1047. * **`'x'` - pad byte**
  1048. * **`'c'` - char (1)**
  1049. * **`'h'` - short (2)**
  1050. * **`'i'` - int (4)**
  1051. * **`'l'` - long (4)**
  1052. * **`'q'` - long long (8)**
  1053. * **`'f'` - float (4)**
  1054. * **`'d'` - double (8)**
  1055. Array
  1056. -----
  1057. **List that can hold only elements of predefined type. Available types are listed above.**
  1058. ```python
  1059. from array import array
  1060. <array> = array('<typecode>' [, <collection>])
  1061. ```
  1062. Memory View
  1063. -----------
  1064. **Used for accessing the internal data of an object that supports the buffer protocol.**
  1065. ```python
  1066. <memoryview> = memoryview(<bytes> / <bytearray> / <array>)
  1067. <memoryview>.release()
  1068. ```
  1069. Deque
  1070. -----
  1071. **Thread-safe list with efficient appends and pops from either side. Pronounced "deck".**
  1072. ```python
  1073. from collections import deque
  1074. <deque> = deque(<collection>, maxlen=None)
  1075. ```
  1076. ```python
  1077. <deque>.appendleft(<el>)
  1078. <el> = <deque>.popleft()
  1079. ```
  1080. ```python
  1081. <deque>.extendleft(<collection>) # Collection gets reversed.
  1082. <deque>.rotate(n=1) # Rotates elements to the right.
  1083. ```
  1084. Threading
  1085. ---------
  1086. ```python
  1087. from threading import Thread, RLock
  1088. ```
  1089. ### Thread
  1090. ```python
  1091. thread = Thread(target=<function>, args=(<first_arg>, ))
  1092. thread.start()
  1093. ...
  1094. thread.join()
  1095. ```
  1096. ### Lock
  1097. ```python
  1098. lock = RLock()
  1099. lock.acquire()
  1100. ...
  1101. lock.release()
  1102. ```
  1103. Hashlib
  1104. -------
  1105. ```python
  1106. >>> import hashlib
  1107. >>> hashlib.md5(<str>.encode()).hexdigest()
  1108. '33d0eba106da4d3ebca17fcd3f4c3d77'
  1109. ```
  1110. Itertools
  1111. ---------
  1112. * **Every function returns an iterator and can accept any collection and/or iterator.**
  1113. * **If you want to print the iterator, you need to pass it to the list() function!**
  1114. ```python
  1115. from itertools import *
  1116. ```
  1117. ### Combinatoric iterators
  1118. ```python
  1119. >>> combinations('abc', 2)
  1120. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  1121. >>> combinations_with_replacement('abc', 2)
  1122. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  1123. ('b', 'b'), ('b', 'c'),
  1124. ('c', 'c')]
  1125. >>> permutations('abc', 2)
  1126. [('a', 'b'), ('a', 'c'),
  1127. ('b', 'a'), ('b', 'c'),
  1128. ('c', 'a'), ('c', 'b')]
  1129. >>> product('ab', '12')
  1130. [('a', '1'), ('a', '2'),
  1131. ('b', '1'), ('b', '2')]
  1132. >>> product([0, 1], repeat=3)
  1133. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  1134. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  1135. ```
  1136. ### Infinite iterators
  1137. ```python
  1138. >>> a = count(5, 2)
  1139. >>> next(a), next(a), next(a)
  1140. (5, 7, 9)
  1141. >>> a = cycle('abc')
  1142. >>> [next(a) for _ in range(10)]
  1143. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  1144. >>> repeat(10, 3)
  1145. [10, 10, 10]
  1146. ```
  1147. ### Iterators
  1148. ```python
  1149. >>> chain([1, 2], [3, 4])
  1150. [1, 2, 3, 4]
  1151. >>> compress([1, 2, 3, 4], [True, False, 1, 0])
  1152. [1, 3]
  1153. >>> # islice(<collection>, from_inclusive, to_exclusive)
  1154. >>> islice([1, 2, 3, 4], 2, None)
  1155. [3, 4]
  1156. ```
  1157. ### Group by
  1158. ```python
  1159. >>> people = [{'id': 1, 'name': 'Bob'},
  1160. {'id': 2, 'name': 'Bob'},
  1161. {'id': 3, 'name': 'Peter'}]
  1162. >>> groups = groupby(people, key=lambda a: a['name'])
  1163. >>> {name: list(group) for name, group in groups}
  1164. {'Bob': [{'id': 1, 'name': 'Bob'},
  1165. {'id': 2, 'name': 'Bob'}],
  1166. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  1167. ```
  1168. Introspection and Metaprograming
  1169. --------------------------------
  1170. **Inspecting code at runtime and code that generates code. You can:**
  1171. * **Look at the attributes**
  1172. * **Set new attributes**
  1173. * **Create functions dynamically**
  1174. * **Traverse the parent classes**
  1175. * **Change values in the class**
  1176. ### Variables
  1177. ```python
  1178. <list> = dir() # Names of in-scope variables.
  1179. <dict> = locals() # Dict of local variables. Also vars().
  1180. <dict> = globals() # Dict of global variables.
  1181. ```
  1182. ### Attributes
  1183. ```python
  1184. class Z:
  1185. def __init__(self):
  1186. self.a = 'abcde'
  1187. self.b = 12345
  1188. ```
  1189. ```python
  1190. >>> z = Z()
  1191. >>> vars(z)
  1192. {'a': 'abcde', 'b': 12345}
  1193. >>> getattr(z, 'a')
  1194. 'abcde'
  1195. >>> hasattr(z, 'c')
  1196. False
  1197. >>> setattr(z, 'c', 10)
  1198. ```
  1199. ### Parameters
  1200. ```python
  1201. from inspect import signature
  1202. sig = signature(<function>)
  1203. no_of_params = len(sig.parameters)
  1204. param_names = list(sig.parameters.keys())
  1205. ```
  1206. ### Type
  1207. **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!).**
  1208. ```python
  1209. <class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
  1210. ```
  1211. ```python
  1212. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1213. >>> z = Z()
  1214. ```
  1215. ### Meta Class
  1216. **Class that creates class.**
  1217. ```python
  1218. def my_meta_class(name, parents, attrs):
  1219. attrs['a'] = 'abcde'
  1220. return type(name, parents, attrs)
  1221. ```
  1222. #### Or:
  1223. ```python
  1224. class MyMetaClass(type):
  1225. def __new__(cls, name, parents, attrs):
  1226. attrs['a'] = 'abcde'
  1227. return type.__new__(cls, name, parents, attrs)
  1228. ```
  1229. ### Metaclass Attribute
  1230. **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.**
  1231. ```python
  1232. class MyClass(metaclass=MyMetaClass):
  1233. b = 12345
  1234. ```
  1235. Operator
  1236. --------
  1237. ```python
  1238. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  1239. eq, ne, lt, le, gt, ge, \
  1240. not_, and_, or_, \
  1241. itemgetter, attrgetter, methodcaller
  1242. ```
  1243. ```python
  1244. import operator as op
  1245. product_of_elems = functools.reduce(op.mul, <list>)
  1246. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1247. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1248. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1249. last_el = op.methodcaller('pop')(<list>)
  1250. ```
  1251. Eval
  1252. ----
  1253. ### Basic
  1254. ```python
  1255. >>> from ast import literal_eval
  1256. >>> literal_eval('1 + 2')
  1257. 3
  1258. >>> literal_eval('[1, 2, 3]')
  1259. [1, 2, 3]
  1260. >>> ast.literal_eval('abs(1)')
  1261. ValueError: malformed node or string
  1262. ```
  1263. ### Using Abstract Syntax Trees
  1264. ```python
  1265. import ast
  1266. from ast import Num, BinOp, UnaryOp
  1267. import operator as op
  1268. LEGAL_OPERATORS = {ast.Add: op.add,
  1269. ast.Sub: op.sub,
  1270. ast.Mult: op.mul,
  1271. ast.Div: op.truediv,
  1272. ast.Pow: op.pow,
  1273. ast.BitXor: op.xor,
  1274. ast.USub: op.neg}
  1275. def evaluate(expression):
  1276. root = ast.parse(expression, mode='eval')
  1277. return eval_node(root.body)
  1278. def eval_node(node):
  1279. node_type = type(node)
  1280. if node_type == Num:
  1281. return node.n
  1282. if node_type not in [BinOp, UnaryOp]:
  1283. raise TypeError(node)
  1284. operator_type = type(node.op)
  1285. if operator_type not in LEGAL_OPERATORS:
  1286. raise TypeError(f'Illegal operator {node.op}')
  1287. operator = LEGAL_OPERATORS[operator_type]
  1288. if node_type == BinOp:
  1289. left, right = eval_node(node.left), eval_node(node.right)
  1290. return operator(left, right)
  1291. elif node_type == UnaryOp:
  1292. operand = eval_node(node.operand)
  1293. return operator(operand)
  1294. ```
  1295. ```python
  1296. >>> evaluate('2 ^ 6')
  1297. 4
  1298. >>> evaluate('2 ** 6')
  1299. 64
  1300. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1301. -5.0
  1302. ```
  1303. Coroutine
  1304. ---------
  1305. * **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().**
  1306. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1307. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1308. ### Helper Decorator
  1309. * **All coroutines must be "primed" by first calling next().**
  1310. * **Remembering to call next() is easy to forget.**
  1311. * **Solved by wrapping coroutines with a decorator:**
  1312. ```python
  1313. def coroutine(func):
  1314. def out(*args, **kwargs):
  1315. cr = func(*args, **kwargs)
  1316. next(cr)
  1317. return cr
  1318. return out
  1319. ```
  1320. ### Pipeline Example
  1321. ```python
  1322. def reader(target):
  1323. for i in range(10):
  1324. target.send(i)
  1325. target.close()
  1326. @coroutine
  1327. def adder(target):
  1328. while True:
  1329. item = (yield)
  1330. target.send(item + 100)
  1331. @coroutine
  1332. def printer():
  1333. while True:
  1334. item = (yield)
  1335. print(item)
  1336. reader(adder(printer())) # 100, 101, ..., 109
  1337. ```
  1338. <br><br>
  1339. Libraries
  1340. =========
  1341. Progress Bar
  1342. ------------
  1343. ```python
  1344. # $ pip3 install tqdm
  1345. from tqdm import tqdm
  1346. from time import sleep
  1347. for i in tqdm([1, 2, 3]):
  1348. sleep(0.2)
  1349. for i in tqdm(range(100)):
  1350. sleep(0.02)
  1351. ```
  1352. Plot
  1353. ----
  1354. ```python
  1355. # $ pip3 install matplotlib
  1356. from matplotlib import pyplot
  1357. pyplot.plot(<data_1> [, <data_2>, ...])
  1358. pyplot.savefig(<filename>, transparent=True)
  1359. pyplot.show()
  1360. ```
  1361. Table
  1362. -----
  1363. #### Prints CSV file as ASCII table:
  1364. ```python
  1365. # $ pip3 install tabulate
  1366. from tabulate import tabulate
  1367. import csv
  1368. with open(<filename>, encoding='utf-8') as file:
  1369. lines = csv.reader(file, delimiter=';')
  1370. headers = [header.title() for header in next(lines)]
  1371. table = tabulate(lines, headers)
  1372. print(table)
  1373. ```
  1374. Curses
  1375. ------
  1376. ```python
  1377. # $ pip3 install curses
  1378. from curses import wrapper
  1379. def main():
  1380. wrapper(draw)
  1381. def draw(screen):
  1382. screen.clear()
  1383. screen.addstr(0, 0, 'Press ESC to quit.')
  1384. while screen.getch() != 27:
  1385. pass
  1386. def get_border(screen):
  1387. from collections import namedtuple
  1388. P = namedtuple('P', 'x y')
  1389. height, width = screen.getmaxyx()
  1390. return P(width - 1, height - 1)
  1391. ```
  1392. Scraping
  1393. --------
  1394. ```python
  1395. # $ pip3 install requests beautifulsoup4
  1396. >>> import requests
  1397. >>> from bs4 import BeautifulSoup
  1398. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1399. >>> page = requests.get(url)
  1400. >>> doc = BeautifulSoup(page.text, 'html.parser')
  1401. >>> table = doc.find('table', class_='infobox vevent')
  1402. >>> rows = table.find_all('tr')
  1403. >>> link = rows[11].find('a')['href']
  1404. >>> ver = rows[6].find('div').text.split()[0]
  1405. >>> link, ver
  1406. ('https://www.python.org/', '3.7.2')
  1407. ```
  1408. Web
  1409. ---
  1410. ```python
  1411. # $ pip3 install bottle
  1412. from bottle import run, route, post, template, request, response
  1413. import json
  1414. ```
  1415. ### Run
  1416. ```python
  1417. run(host='localhost', port=8080)
  1418. run(host='0.0.0.0', port=80, server='cherrypy')
  1419. ```
  1420. ### Static Request
  1421. ```python
  1422. @route('/img/<image>')
  1423. def send_image(image):
  1424. return static_file(image, 'images/', mimetype='image/png')
  1425. ```
  1426. ### Dynamic Request
  1427. ```python
  1428. @route('/<sport>')
  1429. def send_page(sport):
  1430. return template('<h1>{{title}}</h1>', title=sport)
  1431. ```
  1432. ### REST Request
  1433. ```python
  1434. @post('/odds/<sport>')
  1435. def odds_handler(sport):
  1436. team = request.forms.get('team')
  1437. home_odds, away_odds = 2.44, 3.29
  1438. response.headers['Content-Type'] = 'application/json'
  1439. response.headers['Cache-Control'] = 'no-cache'
  1440. return json.dumps([team, home_odds, away_odds])
  1441. ```
  1442. #### Test:
  1443. ```python
  1444. # $ pip3 install requests
  1445. >>> import requests
  1446. >>> url = 'http://localhost:8080/odds/football'
  1447. >>> data = {'team': 'arsenal f.c.'}
  1448. >>> response = requests.post(url, data=data)
  1449. >>> response.json()
  1450. ['arsenal f.c.', 2.44, 3.29]
  1451. ```
  1452. Profile
  1453. -------
  1454. ### Basic
  1455. ```python
  1456. from time import time
  1457. start_time = time() # Seconds since Epoch.
  1458. ...
  1459. duration = time() - start_time
  1460. ```
  1461. ### High Performance
  1462. ```python
  1463. from time import perf_counter as pc
  1464. start_time = pc() # Seconds since restart.
  1465. ...
  1466. duration = pc() - start_time
  1467. ```
  1468. ### Timing a Snippet
  1469. ```python
  1470. from timeit import timeit
  1471. timeit('"-".join(str(a) for a in range(100))',
  1472. number=10000, globals=globals(), setup='pass')
  1473. ```
  1474. ### Line Profiler
  1475. ```python
  1476. # $ pip3 install line_profiler
  1477. @profile
  1478. def main():
  1479. a = [*range(10000)]
  1480. b = {*range(10000)}
  1481. main()
  1482. ```
  1483. #### Usage:
  1484. ```text
  1485. $ kernprof -lv test.py
  1486. Line # Hits Time Per Hit % Time Line Contents
  1487. ==============================================================
  1488. 1 @profile
  1489. 2 def main():
  1490. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1491. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1492. ```
  1493. ### Call Graph
  1494. #### Generates a PNG image of a call graph with highlighted bottlenecks:
  1495. ```python
  1496. # $ pip3 install pycallgraph
  1497. from pycallgraph import output, PyCallGraph
  1498. from datetime import datetime
  1499. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1500. filename = f'profile-{time_str}.png'
  1501. drawer = output.GraphvizOutput(output_file=filename)
  1502. with PyCallGraph(output=drawer):
  1503. <code_to_be_profiled>
  1504. ```
  1505. NumPy
  1506. -----
  1507. **Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.**
  1508. ```python
  1509. # $ pip3 install numpy
  1510. import numpy as np
  1511. ```
  1512. ```python
  1513. <array> = np.array(<list>)
  1514. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1515. <array> = np.ones(<shape>)
  1516. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1517. ```
  1518. ```python
  1519. <array>.shape = <shape>
  1520. <view> = <array>.reshape(<shape>)
  1521. <view> = np.broadcast_to(<array>, <shape>)
  1522. ```
  1523. ```python
  1524. <array> = <array>.sum(<axis>)
  1525. indexes = <array>.argmin(<axis>)
  1526. ```
  1527. * **Shape is a tuple of dimension sizes.**
  1528. * **Axis is an index of dimension that gets collapsed.**
  1529. ### Indexing
  1530. ```bash
  1531. <el> = <2d_array>[0, 0] # First element.
  1532. <1d_view> = <2d_array>[0] # First row.
  1533. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  1534. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  1535. ```
  1536. ```bash
  1537. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  1538. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  1539. ```
  1540. ```bash
  1541. <2d_bools> = <2d_array> > 0
  1542. <1d_array> = <2d_array>[<2d_bools>]
  1543. ```
  1544. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  1545. ### Broadcasting
  1546. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1547. ```python
  1548. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1549. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1550. ```
  1551. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1552. ```python
  1553. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1554. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1555. ```
  1556. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1557. ```python
  1558. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1559. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1560. ```
  1561. #### 3. If neither non-matching dimension has size 1, rise an error.
  1562. ### Example
  1563. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1564. ```python
  1565. >>> points = np.array([0.1, 0.6, 0.8])
  1566. [ 0.1, 0.6, 0.8]
  1567. >>> wrapped_points = points.reshape(3, 1)
  1568. [[ 0.1],
  1569. [ 0.6],
  1570. [ 0.8]]
  1571. >>> distances = wrapped_points - points
  1572. [[ 0. , -0.5, -0.7],
  1573. [ 0.5, 0. , -0.2],
  1574. [ 0.7, 0.2, 0. ]]
  1575. >>> distances = np.abs(distances)
  1576. [[ 0. , 0.5, 0.7],
  1577. [ 0.5, 0. , 0.2],
  1578. [ 0.7, 0.2, 0. ]]
  1579. >>> i = np.arange(3)
  1580. [0, 1, 2]
  1581. >>> distances[i, i] = np.inf
  1582. [[ inf, 0.5, 0.7],
  1583. [ 0.5, inf, 0.2],
  1584. [ 0.7, 0.2, inf]]
  1585. >>> distances.argmin(1)
  1586. [1, 2, 1]
  1587. ```
  1588. Image
  1589. -----
  1590. ```python
  1591. # $ pip3 install pillow
  1592. from PIL import Image
  1593. ```
  1594. #### Creates PNG image of rainbow gradient:
  1595. ```python
  1596. width = 100
  1597. height = 100
  1598. size = width * height
  1599. pixels = [255 * i/size for i in range(size)]
  1600. img = Image.new('HSV', (width, height))
  1601. img.putdata([(int(a), 255, 255) for a in pixels])
  1602. img.convert(mode='RGB').save('test.png')
  1603. ```
  1604. #### Adds noise to a PNG image:
  1605. ```python
  1606. from random import randint
  1607. add_noise = lambda value: max(0, min(255, value + randint(-20, 20)))
  1608. img = Image.open('test.png').convert(mode='HSV')
  1609. img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
  1610. img.convert(mode='RGB').save('test.png')
  1611. ```
  1612. ### Modes
  1613. * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.**
  1614. * **`'L'` - 8-bit pixels, greyscale.**
  1615. * **`'RGB'` - 3x8-bit pixels, true color.**
  1616. * **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.**
  1617. * **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.**
  1618. Audio
  1619. -----
  1620. ```python
  1621. import wave
  1622. from struct import pack, iter_unpack
  1623. ```
  1624. ### Read Frames from WAV File
  1625. ```python
  1626. def read_wav_file(filename):
  1627. with wave.open(filename, 'rb') as wf:
  1628. frames = wf.readframes(wf.getnframes())
  1629. return [a[0] for a in iter_unpack('<h', frames)]
  1630. ```
  1631. ### Write Frames to WAV File
  1632. ```python
  1633. def write_to_wav_file(filename, frames_int, mono=True):
  1634. frames_short = (pack('<h', a) for a in frames_int)
  1635. with wave.open(filename, 'wb') as wf:
  1636. wf.setnchannels(1 if mono else 2)
  1637. wf.setsampwidth(2)
  1638. wf.setframerate(44100)
  1639. wf.writeframes(b''.join(frames_short))
  1640. ```
  1641. ### Examples
  1642. #### Saves a sine wave to a mono WAV file:
  1643. ```python
  1644. from math import pi, sin
  1645. frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
  1646. frames_i = (int(a * 30000) for a in frames_f)
  1647. write_to_wav_file('test.wav', frames_i)
  1648. ```
  1649. #### Adds noise to a mono WAV file:
  1650. ```python
  1651. from random import randint
  1652. add_noise = lambda value: max(-32768, min(32767, value + randint(-500, 500)))
  1653. frames_i = (add_noise(a) for a in read_wav_file('test.wav'))
  1654. write_to_wav_file('test.wav', frames_i)
  1655. ```
  1656. #### Plays Popcorn:
  1657. ```python
  1658. # pip3 install simpleaudio
  1659. import simpleaudio, math, struct
  1660. from itertools import chain, repeat
  1661. F = 44100
  1662. P1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,'
  1663. P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'
  1664. get_pause = lambda seconds: repeat(0, int(seconds * F))
  1665. sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
  1666. get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
  1667. get_hz = lambda n: 8.176 * 2 ** (int(n) / 12)
  1668. parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125)
  1669. get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125)
  1670. frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(','))
  1671. frames_b = b''.join(struct.pack('<h', int(a * 30000)) for a in frames_i)
  1672. simpleaudio.play_buffer(frames_b, 1, 2, F)
  1673. ```
  1674. Basic Script Template
  1675. ---------------------
  1676. ```python
  1677. #!/usr/bin/env python3
  1678. #
  1679. # Usage: .py
  1680. #
  1681. from collections import namedtuple
  1682. from enum import Enum
  1683. import re
  1684. import sys
  1685. def main():
  1686. pass
  1687. ###
  1688. ## UTIL
  1689. #
  1690. def read_file(filename):
  1691. with open(filename, encoding='utf-8') as file:
  1692. return file.readlines()
  1693. if __name__ == '__main__':
  1694. main()
  1695. ```