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

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