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.

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