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.

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