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.

2061 lines
48 KiB

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