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.

2094 lines
50 KiB

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