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.

2184 lines
55 KiB

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