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.

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