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.

2033 lines
48 KiB

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