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.

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