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.

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