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.

2109 lines
53 KiB

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