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.

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