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.

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