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.

2111 lines
53 KiB

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