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.

2236 lines
56 KiB

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