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.

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