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.

2835 lines
83 KiB

6 years ago
7 years ago
5 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
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
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
6 years ago
5 years ago
7 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
7 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
5 years ago
5 years ago
5 years ago
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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
6 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
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
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
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
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
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
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
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
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
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
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
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
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
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
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
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
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
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
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
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
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
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
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
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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. <sup>[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md), [PDF](https://gto76.github.io/python-cheatsheet/web/python-cheatsheet-eea110f.pdf), [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)**__,__ **[`Dictionary`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__
  9. **&nbsp;&nbsp;&nbsp;** **2. Types:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regular_Exp`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__
  10. **&nbsp;&nbsp;&nbsp;** **3. Syntax:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exceptions`](#exceptions)**__.__
  11. **&nbsp;&nbsp;&nbsp;** **4. System:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#path)**__,__ **[`Command_Execution`](#oscommands)**__.__
  12. **&nbsp;&nbsp;&nbsp;** **5. Data:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`MemoryView`](#memory-view)**__,__ **[`Deque`](#deque)**__.__
  13. **&nbsp;&nbsp;&nbsp;** **6. Advanced:** **&nbsp;&nbsp;&nbsp;** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprograming)**__,__ **[`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`](#profiling)**__,__
  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)**__,__ **[`Animation`](#animation)**__,__ **[`Audio`](#audio)**__,__ **[`Synthesizer`](#synthesizer)**__.__
  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. <int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
  48. index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
  49. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  50. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  51. <list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
  52. <list>.clear() # Removes all items. Also works on dictionary and set.
  53. ```
  54. Dictionary
  55. ----------
  56. ```python
  57. <view> = <dict>.keys() # Coll. of keys that reflects changes.
  58. <view> = <dict>.values() # Coll. of values that reflects changes.
  59. <view> = <dict>.items() # Coll. of key-value tuples.
  60. ```
  61. ```python
  62. value = <dict>.get(key, default=None) # Returns default if key is missing.
  63. value = <dict>.setdefault(key, default=None) # Returns and writes default if key is missing.
  64. <dict> = collections.defaultdict(<type>) # Creates a dict with default value of type.
  65. <dict> = collections.defaultdict(lambda: 1) # Creates a dict with default value 1.
  66. ```
  67. ```python
  68. <dict>.update(<dict>)
  69. <dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
  70. <dict> = dict(zip(keys, values)) # Creates a dict from two collections.
  71. <dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
  72. ```
  73. ```python
  74. value = <dict>.pop(key) # Removes item or raises KeyError.
  75. {k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
  76. ```
  77. ### Counter
  78. ```python
  79. >>> from collections import Counter
  80. >>> colors = ['blue', 'red', 'blue', 'red', 'blue']
  81. >>> counter = Counter(colors)
  82. >>> counter['yellow'] += 1
  83. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  84. >>> counter.most_common()[0]
  85. ('blue', 3)
  86. ```
  87. Set
  88. ---
  89. ```python
  90. <set> = set()
  91. ```
  92. ```python
  93. <set>.add(<el>) # Or: <set> |= {<el>}
  94. <set>.update(<collection>) # Or: <set> |= <set>
  95. ```
  96. ```python
  97. <set> = <set>.union(<coll.>) # Or: <set> | <set>
  98. <set> = <set>.intersection(<coll.>) # Or: <set> & <set>
  99. <set> = <set>.difference(<coll.>) # Or: <set> - <set>
  100. <set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
  101. <bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
  102. <bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
  103. ```
  104. ```python
  105. <el> = <set>.pop() # Raises KeyError if empty.
  106. <set>.remove(<el>) # Raises KeyError if missing.
  107. <set>.discard(<el>) # Doesn't raise an error.
  108. ```
  109. ### Frozen Set
  110. * **Is immutable and hashable.**
  111. * **That means it can be used as a key in a dictionary or as an element in a set.**
  112. ```python
  113. <frozenset> = frozenset(<collection>)
  114. ```
  115. Tuple
  116. -----
  117. **Tuple is an immutable and hashable list.**
  118. ```python
  119. <tuple> = ()
  120. <tuple> = (<el>, )
  121. <tuple> = (<el_1>, <el_2> [, ...])
  122. ```
  123. ### Named Tuple
  124. **Tuple's subclass with named elements.**
  125. ```python
  126. >>> from collections import namedtuple
  127. >>> Point = namedtuple('Point', 'x y')
  128. >>> p = Point(1, y=2)
  129. Point(x=1, y=2)
  130. >>> p[0]
  131. 1
  132. >>> p.x
  133. 1
  134. >>> getattr(p, 'y')
  135. 2
  136. >>> p._fields # Or: Point._fields
  137. ('x', 'y')
  138. ```
  139. Range
  140. -----
  141. ```python
  142. <range> = range(to_exclusive)
  143. <range> = range(from_inclusive, to_exclusive)
  144. <range> = range(from_inclusive, to_exclusive, ±step_size)
  145. ```
  146. ```python
  147. from_inclusive = <range>.start
  148. to_exclusive = <range>.stop
  149. ```
  150. Enumerate
  151. ---------
  152. ```python
  153. for i, el in enumerate(<collection> [, i_start]):
  154. ...
  155. ```
  156. Iterator
  157. --------
  158. ```python
  159. <iter> = iter(<collection>) # `iter(<iter>)` returns unmodified iterator.
  160. <iter> = iter(<function>, to_exclusive) # Sequence of return values until 'to_exclusive'.
  161. <el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
  162. ```
  163. ### Itertools
  164. ```python
  165. from itertools import count, repeat, cycle, chain, islice
  166. ```
  167. ```python
  168. <iter> = count(start=0, step=1) # Returns incremented value endlessly.
  169. <iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times.
  170. <iter> = cycle(<collection>) # Repeats the sequence indefinitely.
  171. ```
  172. ```python
  173. <iter> = chain(<coll_1>, <coll_2> [, ...]) # Empties collections in order.
  174. <iter> = chain.from_iterable(<collection>) # Empties collections inside a collection in order.
  175. ```
  176. ```python
  177. <iter> = islice(<collection>, to_exclusive)
  178. <iter> = islice(<collection>, from_inclusive, to_exclusive)
  179. <iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)
  180. ```
  181. Generator
  182. ---------
  183. * **Any function that contains a yield statement returns a generator.**
  184. * **Generators and iterators are interchangeable.**
  185. ```python
  186. def count(start, step):
  187. while True:
  188. yield start
  189. start += step
  190. ```
  191. ```python
  192. >>> counter = count(10, 2)
  193. >>> next(counter), next(counter), next(counter)
  194. (10, 12, 14)
  195. ```
  196. Type
  197. ----
  198. * **Everything is an object.**
  199. * **Every object has a type.**
  200. * **Type and class are synonymous.**
  201. ```python
  202. <type> = type(<el>) # Or: <el>.__class__
  203. <bool> = isinstance(<el>, <type>) # Or: issubclass(type(<el>), <type>)
  204. ```
  205. ```python
  206. >>> type('a'), 'a'.__class__, str
  207. (<class 'str'>, <class 'str'>, <class 'str'>)
  208. ```
  209. #### Some types do not have built-in names, so they must be imported:
  210. ```python
  211. from types import FunctionType, MethodType, LambdaType, GeneratorType
  212. ```
  213. ### ABC
  214. **An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**
  215. ```python
  216. >>> from collections.abc import Sequence, Collection, Iterable
  217. >>> isinstance([1, 2, 3], Iterable)
  218. True
  219. ```
  220. ```text
  221. +------------------+----------+------------+----------+
  222. | | Sequence | Collection | Iterable |
  223. +------------------+----------+------------+----------+
  224. | list, range, str | yes | yes | yes |
  225. | dict, set | | yes | yes |
  226. | iter | | | yes |
  227. +------------------+----------+------------+----------+
  228. ```
  229. ```python
  230. >>> from numbers import Integral, Rational, Real, Complex, Number
  231. >>> isinstance(123, Number)
  232. True
  233. ```
  234. ```text
  235. +--------------------+----------+----------+--------+---------+--------+
  236. | | Integral | Rational | Real | Complex | Number |
  237. +--------------------+----------+----------+--------+---------+--------+
  238. | int | yes | yes | yes | yes | yes |
  239. | fractions.Fraction | | yes | yes | yes | yes |
  240. | float | | | yes | yes | yes |
  241. | complex | | | | yes | yes |
  242. | decimal.Decimal | | | | | yes |
  243. +--------------------+----------+----------+--------+---------+--------+
  244. ```
  245. String
  246. ------
  247. ```python
  248. <str> = <str>.strip() # Strips all whitespace characters from both ends.
  249. <str> = <str>.strip('<chars>') # Strips all passed characters from both ends.
  250. ```
  251. ```python
  252. <list> = <str>.split() # Splits on one or more whitespace characters.
  253. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
  254. <list> = <str>.splitlines(keepends=False) # Splits on line breaks. Keeps them if 'keepends'.
  255. <str> = <str>.join(<coll_of_strings>) # Joins elements using string as separator.
  256. ```
  257. ```python
  258. <bool> = <sub_str> in <str> # Checks if string contains a substring.
  259. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  260. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  261. <int> = <str>.find(<sub_str>) # Returns start index of first match or -1.
  262. <int> = <str>.index(<sub_str>) # Same but raises ValueError if missing.
  263. ```
  264. ```python
  265. <str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
  266. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  267. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  268. ```
  269. * **Also: `'lstrip()'`, `'rstrip()'`.**
  270. * **Also: `'lower()'`, `'upper()'`, `'capitalize()'` and `'title()'`.**
  271. ### Char
  272. ```python
  273. <str> = chr(<int>) # Converts int to unicode char.
  274. <int> = ord(<str>) # Converts unicode char to int.
  275. ```
  276. ```python
  277. >>> ord('0'), ord('9')
  278. (48, 57)
  279. >>> ord('A'), ord('Z')
  280. (65, 90)
  281. >>> ord('a'), ord('z')
  282. (97, 122)
  283. ```
  284. Regex
  285. -----
  286. ```python
  287. import re
  288. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  289. <list> = re.findall(<regex>, text) # Returns all occurrences.
  290. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  291. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  292. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  293. <iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.
  294. ```
  295. * **Search() and match() return None if they can't find a match.**
  296. * **Argument `'flags=re.IGNORECASE'` can be used with all functions.**
  297. * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
  298. * **Argument `'flags=re.DOTALL'` makes dot also accept newline.**
  299. * **Use `r'\1'` or `'\\1'` for backreference.**
  300. * **Add `'?'` after an operator to make it non-greedy.**
  301. ### Match Object
  302. ```python
  303. <str> = <Match>.group() # Whole match. Also group(0).
  304. <str> = <Match>.group(1) # Part in first bracket.
  305. <tuple> = <Match>.groups() # All bracketed parts.
  306. <int> = <Match>.start() # Start index of a match.
  307. <int> = <Match>.end() # Exclusive end index of a match.
  308. ```
  309. ### Special Sequences
  310. * **By default digits, whitespaces and alphanumerics from all alphabets are matched, unless `'flags=re.ASCII'` argument is used.**
  311. * **Use capital letters for negation.**
  312. ```python
  313. '\d' == '[0-9]' # Digit
  314. '\s' == '[ \t\n\r\f\v]' # Whitespace
  315. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  316. ```
  317. Format
  318. ------
  319. ```python
  320. <str> = f'{<el_1>}, {<el_2>}'
  321. <str> = '{}, {}'.format(<el_1>, <el_2>)
  322. ```
  323. ### Attributes
  324. ```python
  325. >>> from collections import namedtuple
  326. >>> Person = namedtuple('Person', 'name height')
  327. >>> person = Person('Jean-Luc', 187)
  328. >>> f'{person.height}'
  329. '187'
  330. >>> '{p.height}'.format(p=person)
  331. '187'
  332. ```
  333. ### General Options
  334. ```python
  335. {<el>:<10} # '<el> '
  336. {<el>:^10} # ' <el> '
  337. {<el>:>10} # ' <el>'
  338. ```
  339. ```python
  340. {<el>:.<10} # '<el>......'
  341. {<el>:<0} # '<el>'
  342. ```
  343. ### Strings
  344. **`'!r'` calls object's repr() method, instead of str(), to get a string.**
  345. ```python
  346. {'abcde'!r:<10} # "'abcde' "
  347. {'abcde':.3} # 'abc'
  348. {'abcde':10.3} # 'abc '
  349. ```
  350. ### Numbers
  351. ```python
  352. { 123456:10,} # ' 123,456'
  353. { 123456:10_} # ' 123_456'
  354. { 123456:+10} # ' +123456'
  355. {-123456:=10} # '- 123456'
  356. { 123456: } # ' 123456'
  357. {-123456: } # '-123456'
  358. ```
  359. ### Floats
  360. ```python
  361. {1.23456:10.3} # ' 1.23'
  362. {1.23456:10.3f} # ' 1.235'
  363. {1.23456:10.3e} # ' 1.235e+00'
  364. {1.23456:10.3%} # ' 123.456%'
  365. ```
  366. #### Comparison of float presentation types:
  367. ```text
  368. +----------------+----------------+---------------+----------------+-----------------+
  369. | | {<float>} | {<float>:f} | {<float>:e} | {<float>:%} |
  370. +----------------+----------------+---------------+----------------+-----------------+
  371. | 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
  372. | 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
  373. | 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
  374. | 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
  375. | 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
  376. | 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
  377. | 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
  378. | 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' |
  379. +----------------+----------------+---------------+----------------+-----------------+
  380. ```
  381. ```text
  382. +----------------+----------------+---------------+----------------+-----------------+
  383. | | {<float>:.2} | {<float>:.2f} | {<float>:.2e} | {<float>:.2%} |
  384. +----------------+----------------+---------------+----------------+-----------------+
  385. | 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
  386. | 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
  387. | 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
  388. | 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
  389. | 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
  390. | 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
  391. | 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
  392. | 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' |
  393. +----------------+----------------+---------------+----------------+-----------------+
  394. ```
  395. ### Ints
  396. ```python
  397. {90:c} # 'Z'
  398. {90:X} # '5A'
  399. {90:b} # '1011010'
  400. ```
  401. Numbers
  402. -------
  403. ### Types
  404. ```python
  405. <int> = int(<float/str/bool>) # Or: math.floor(<float>)
  406. <float> = float(<int/str/bool>)
  407. <complex> = complex(real=0, imag=0) # Or: <real> + <real>j
  408. <Fraction> = fractions.Fraction(numerator=0, denominator=1)
  409. <Decimal> = decimal.Decimal(<str/int/float>)
  410. ```
  411. * **`'int(<str>)'` and `'float(<str>)'` raise ValueError on malformed strings.**
  412. * **Decimal numbers can be represented exactly, unlike floats where `'1.1 + 2.2 != 3.3'`.**
  413. * **Their precision can be adjusted with `'decimal.getcontext().prec = <int>'`.**
  414. ### Basic Functions
  415. ```python
  416. <num> = pow(<num>, <num>) # Or: <num> ** <num>
  417. <num> = abs(<num>)
  418. <int> = round(<num>)
  419. <num> = round(<num>, ±ndigits) # `round(126, -1) == 130`
  420. ```
  421. ### Math
  422. ```python
  423. from math import e, pi, inf, nan
  424. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  425. from math import log, log10, log2
  426. ```
  427. ### Statistics
  428. ```python
  429. from statistics import mean, median, variance, pvariance, pstdev
  430. ```
  431. ### Random
  432. ```python
  433. from random import random, randint, choice, shuffle
  434. <float> = random()
  435. <int> = randint(from_inclusive, to_inclusive)
  436. <el> = choice(<list>)
  437. shuffle(<list>)
  438. ```
  439. ### Bin, Hex
  440. ```python
  441. <int> = 0b<bin> # Or: 0x<hex>
  442. <int> = int('<bin>', 2) # Or: int('<hex>', 16)
  443. <int> = int('0b<bin>', 0) # Or: int('0x<hex>', 0)
  444. '0b<bin>' = bin(<int>) # Or: '0x<hex>' = hex(<int>)
  445. ```
  446. ### Bitwise Operators
  447. ```python
  448. <int> = <int> & <int> # And
  449. <int> = <int> | <int> # Or
  450. <int> = <int> ^ <int> # Xor (0 if both bits equal)
  451. <int> = <int> << n_bits # Shift left
  452. <int> = <int> >> n_bits # Shift right
  453. <int> = ~<int> # Compliment (flips bits)
  454. ```
  455. Combinatorics
  456. -------------
  457. * **Every function returns an iterator.**
  458. * **If you want to print the iterator, you need to pass it to the list() function!**
  459. ```python
  460. from itertools import product, combinations, combinations_with_replacement, permutations
  461. ```
  462. ```python
  463. >>> product([0, 1], repeat=3)
  464. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  465. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  466. ```
  467. ```python
  468. >>> product('ab', '12')
  469. [('a', '1'), ('a', '2'),
  470. ('b', '1'), ('b', '2')]
  471. ```
  472. ```python
  473. >>> combinations('abc', 2)
  474. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  475. ```
  476. ```python
  477. >>> combinations_with_replacement('abc', 2)
  478. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  479. ('b', 'b'), ('b', 'c'),
  480. ('c', 'c')]
  481. ```
  482. ```python
  483. >>> permutations('abc', 2)
  484. [('a', 'b'), ('a', 'c'),
  485. ('b', 'a'), ('b', 'c'),
  486. ('c', 'a'), ('c', 'b')]
  487. ```
  488. Datetime
  489. --------
  490. * **Module 'datetime' provides 'date' `<D>`, 'time' `<T>`, 'datetime' `<DT>` and 'timedelta' `<TD>` classes. All are immutable and hashable.**
  491. * **Time and datetime can be 'aware' `<a>`, meaning they have defined timezone, or 'naive' `<n>`, meaning they don't.**
  492. * **If object is naive it is presumed to be in the system's timezone.**
  493. ```python
  494. from datetime import date, time, datetime, timedelta
  495. from dateutil.tz import UTC, tzlocal, gettz
  496. ```
  497. ### Constructors
  498. ```python
  499. <D> = date(year, month, day)
  500. <T> = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
  501. <DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
  502. <TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
  503. minutes=0, hours=0, weeks=0)
  504. ```
  505. * **Use `'<D/DT>.weekday()'` to get the day of the week (Mon == 0).**
  506. * **`'fold=1'` means second pass in case of time jumping back for one hour.**
  507. ### Now
  508. ```python
  509. <D/DTn> = D/DT.today() # Current local date or naive datetime.
  510. <DTn> = DT.utcnow() # Naive datetime from current UTC time.
  511. <DTa> = DT.now(<tzinfo>) # Aware datetime from current tz time.
  512. ```
  513. * **To extract time use `'<DTn>.time()'`, `'<DTa>.time()'` or `'<DTa>.timetz()'`.**
  514. ### Timezone
  515. ```python
  516. <tzinfo> = UTC # UTC timezone. London without DST.
  517. <tzinfo> = tzlocal() # Local timezone. Also gettz().
  518. <tzinfo> = gettz('<Cont.>/<City>') # 'Continent/City_Name' timezone or None.
  519. ```
  520. ```python
  521. <DTa> = <DT>.astimezone(<tzinfo>) # Datetime, converted to passed timezone.
  522. <Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Unconverted object with new timezone.
  523. ```
  524. ### Encode
  525. ```python
  526. <D/T/DT> = D/T/DT.fromisoformat('<iso>') # Object from ISO string. Raises ValueError.
  527. <DT> = DT.strptime(<str>, '<format>') # Datetime from str, according to format.
  528. <D/DTn> = D/DT.fromordinal(<int>) # D/DTn from days since Christ, at midnight.
  529. <DTn> = DT.fromtimestamp(<real>) # Local time DTn from seconds since Epoch.
  530. <DTa> = DT.fromtimestamp(<real>, <tz.>) # Aware datetime from seconds since Epoch.
  531. ```
  532. * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±<offset>]'`, or both separated by a space or a `'T'`. Offset is formatted as: `'HH:MM'`.**
  533. * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...**
  534. ### Decode
  535. ```python
  536. <str> = <D/T/DT>.isoformat() # ISO string representation.
  537. <str> = <D/T/DT>.strftime('<format>') # Custom string representation.
  538. <int> = <D/DT>.toordinal() # Days since Christ, ignoring time and tz.
  539. <float> = <DTn>.timestamp() # Seconds since Epoch from DTn in local time.
  540. <float> = <DTa>.timestamp() # Seconds since Epoch from DTa.
  541. ```
  542. ### Format
  543. ```python
  544. >>> from datetime import datetime
  545. >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
  546. >>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z")
  547. "Thursday, 14th of May '15, 11:39PM UTC+02:00"
  548. ```
  549. * **When parsing, `'%z'` also accepts `'±HH:MM'`.**
  550. * **For abbreviated weekday and month use `'%a'` and `'%b'`.**
  551. ### Arithmetics
  552. ```python
  553. <TD> = <D/DT> - <D/DT>
  554. <D/DT> = <D/DT> ± <TD>
  555. <TD> = <TD> ± <TD>
  556. <TD> = <TD> */ <real>
  557. ```
  558. Arguments
  559. ---------
  560. ### Inside Function Call
  561. ```python
  562. <function>(<positional_args>) # f(0, 0)
  563. <function>(<keyword_args>) # f(x=0, y=0)
  564. <function>(<positional_args>, <keyword_args>) # f(0, y=0)
  565. ```
  566. ### Inside Function Definition
  567. ```python
  568. def f(<nondefault_args>): # def f(x, y):
  569. def f(<default_args>): # def f(x=0, y=0):
  570. def f(<nondefault_args>, <default_args>): # def f(x, y=0):
  571. ```
  572. Splat Operator
  573. --------------
  574. ### Inside Function Call
  575. **Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.**
  576. ```python
  577. args = (1, 2)
  578. kwargs = {'x': 3, 'y': 4, 'z': 5}
  579. func(*args, **kwargs)
  580. ```
  581. #### Is the same as:
  582. ```python
  583. func(1, 2, x=3, y=4, z=5)
  584. ```
  585. ### Inside Function Definition
  586. **Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.**
  587. ```python
  588. def add(*a):
  589. return sum(a)
  590. ```
  591. ```python
  592. >>> add(1, 2, 3)
  593. 6
  594. ```
  595. #### Legal argument combinations:
  596. ```python
  597. def f(x, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
  598. def f(*, x, y, z): # f(x=1, y=2, z=3)
  599. def f(x, *, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
  600. def f(x, y, *, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
  601. ```
  602. ```python
  603. def f(*args): # f(1, 2, 3)
  604. def f(x, *args): # f(1, 2, 3)
  605. def f(*args, z): # f(1, 2, z=3)
  606. def f(x, *args, z): # f(1, 2, z=3)
  607. ```
  608. ```python
  609. def f(**kwargs): # f(x=1, y=2, z=3)
  610. def f(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
  611. def f(*, x, **kwargs): # f(x=1, y=2, z=3)
  612. ```
  613. ```python
  614. 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)
  615. 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)
  616. def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
  617. def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
  618. ```
  619. ### Other Uses
  620. ```python
  621. <list> = [*<collection> [, ...]]
  622. <set> = {*<collection> [, ...]}
  623. <tuple> = (*<collection>, [...])
  624. <dict> = {**<dict> [, ...]}
  625. ```
  626. ```python
  627. head, *body, tail = <collection>
  628. ```
  629. Inline
  630. ------
  631. ### Lambda
  632. ```python
  633. <function> = lambda: <return_value>
  634. <function> = lambda <argument_1>, <argument_2>: <return_value>
  635. ```
  636. ### Comprehension
  637. ```python
  638. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  639. <set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
  640. <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
  641. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  642. ```
  643. ```python
  644. out = [i+j for i in range(10) for j in range(10)]
  645. ```
  646. #### Is the same as:
  647. ```python
  648. out = []
  649. for i in range(10):
  650. for j in range(10):
  651. out.append(i+j)
  652. ```
  653. ### Map, Filter, Reduce
  654. ```python
  655. from functools import reduce
  656. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  657. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
  658. <obj> = reduce(lambda out, x: out + x, range(10)) # 45
  659. ```
  660. ### Any, All
  661. ```python
  662. <bool> = any(<collection>) # False if empty.
  663. <bool> = all(el[1] for el in <collection>) # True if empty.
  664. ```
  665. ### If - Else
  666. ```python
  667. <expression_if_true> if <condition> else <expression_if_false>
  668. ```
  669. ```python
  670. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  671. ['zero', 1, 'zero', 3]
  672. ```
  673. ### Namedtuple, Enum, Dataclass
  674. ```python
  675. from collections import namedtuple
  676. Point = namedtuple('Point', 'x y')
  677. point = Point(0, 0)
  678. ```
  679. ```python
  680. from enum import Enum
  681. Direction = Enum('Direction', 'n e s w')
  682. direction = Direction.n
  683. ```
  684. ```python
  685. from dataclasses import make_dataclass
  686. Creature = make_dataclass('Creature', ['location', 'direction'])
  687. creature = Creature(Point(0, 0), Direction.n)
  688. ```
  689. Closure
  690. -------
  691. **We have a closure in Python when:**
  692. * **A nested function references a value of its enclosing function and then**
  693. * **the enclosing function returns the nested function.**
  694. ```python
  695. def get_multiplier(a):
  696. def out(b):
  697. return a * b
  698. return out
  699. ```
  700. ```python
  701. >>> multiply_by_3 = get_multiplier(3)
  702. >>> multiply_by_3(10)
  703. 30
  704. ```
  705. * **If multiple nested functions within enclosing function reference the same value, that value gets shared.**
  706. * **To dynamically access function's first free variable use `'<function>.__closure__[0].cell_contents'`.**
  707. ### Partial
  708. ```python
  709. from functools import partial
  710. <function> = partial(<function> [, <arg_1>, <arg_2>, ...])
  711. ```
  712. ```python
  713. >>> import operator as op
  714. >>> multiply_by_3 = partial(op.mul, 3)
  715. >>> multiply_by_3(10)
  716. 30
  717. ```
  718. * **Partial is also useful in cases when a function needs to be passed as an argument, because it enables us to set its arguments beforehand.**
  719. * **A few examples being `'defaultdict(<function>)'`, `'iter(<function>, to_exclusive)'` and dataclass's `'field(default_factory=<function>)'`.**
  720. ### Nonlocal
  721. **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'.**
  722. ```python
  723. def get_counter():
  724. i = 0
  725. def out():
  726. nonlocal i
  727. i += 1
  728. return i
  729. return out
  730. ```
  731. ```python
  732. >>> counter = get_counter()
  733. >>> counter(), counter(), counter()
  734. (1, 2, 3)
  735. ```
  736. Decorator
  737. ---------
  738. **A decorator takes a function, adds some functionality and returns it.**
  739. ```python
  740. @decorator_name
  741. def function_that_gets_passed_to_decorator():
  742. ...
  743. ```
  744. ### Debugger Example
  745. **Decorator that prints function's name every time it gets called.**
  746. ```python
  747. from functools import wraps
  748. def debug(func):
  749. @wraps(func)
  750. def out(*args, **kwargs):
  751. print(func.__name__)
  752. return func(*args, **kwargs)
  753. return out
  754. @debug
  755. def add(x, y):
  756. return x + y
  757. ```
  758. * **Wraps is a helper decorator that copies metadata of function func() to function out().**
  759. * **Without it `'add.__name__'` would return `'out'`.**
  760. ### LRU Cache
  761. **Decorator that caches function's return values. All function's arguments must be hashable.**
  762. ```python
  763. from functools import lru_cache
  764. @lru_cache(maxsize=None)
  765. def fib(n):
  766. return n if n < 2 else fib(n-2) + fib(n-1)
  767. ```
  768. * **Recursion depth is limited to 1000 by default. To increase it use `'sys.setrecursionlimit(<depth>)'`.**
  769. ### Parametrized Decorator
  770. **A decorator that accepts arguments and returns a normal decorator that accepts a function.**
  771. ```python
  772. from functools import wraps
  773. def debug(print_result=False):
  774. def decorator(func):
  775. @wraps(func)
  776. def out(*args, **kwargs):
  777. result = func(*args, **kwargs)
  778. print(func.__name__, result if print_result else '')
  779. return result
  780. return out
  781. return decorator
  782. @debug(print_result=True)
  783. def add(x, y):
  784. return x + y
  785. ```
  786. Class
  787. -----
  788. ```python
  789. class <name>:
  790. def __init__(self, a):
  791. self.a = a
  792. def __repr__(self):
  793. class_name = self.__class__.__name__
  794. return f'{class_name}({self.a!r})'
  795. def __str__(self):
  796. return str(self.a)
  797. @classmethod
  798. def get_class_name(cls):
  799. return cls.__name__
  800. ```
  801. * **Return value of repr() should be unambiguous and of str() readable.**
  802. * **If only repr() is defined, it will also be used for str().**
  803. #### Str() use cases:
  804. ```python
  805. print(<el>)
  806. print(f'{<el>}')
  807. raise Exception(<el>)
  808. loguru.logger.debug(<el>)
  809. csv.writer(<file>).writerow([<el>])
  810. ```
  811. #### Repr() use cases:
  812. ```python
  813. print([<el>])
  814. print(f'{<el>!r}')
  815. >>> <el>
  816. loguru.logger.exception()
  817. Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
  818. ```
  819. ### Constructor Overloading
  820. ```python
  821. class <name>:
  822. def __init__(self, a=None):
  823. self.a = a
  824. ```
  825. ### Inheritance
  826. ```python
  827. class Person:
  828. def __init__(self, name, age):
  829. self.name = name
  830. self.age = age
  831. class Employee(Person):
  832. def __init__(self, name, age, staff_num):
  833. super().__init__(name, age)
  834. self.staff_num = staff_num
  835. ```
  836. ### Multiple Inheritance
  837. ```python
  838. class A: pass
  839. class B: pass
  840. class C(A, B): pass
  841. ```
  842. **MRO determines the order in which parent classes are traversed when searching for a method:**
  843. ```python
  844. >>> C.mro()
  845. [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
  846. ```
  847. ### Property
  848. ```python
  849. class MyClass:
  850. @property
  851. def a(self):
  852. return self._a
  853. @a.setter
  854. def a(self, value):
  855. self._a = value
  856. ```
  857. ```python
  858. >>> el = MyClass()
  859. >>> el.a = 123
  860. >>> el.a
  861. 123
  862. ```
  863. ### Dataclass
  864. **Decorator that automatically generates init(), repr() and eq() special methods.**
  865. ```python
  866. from dataclasses import dataclass, field
  867. @dataclass(order=False, frozen=False)
  868. class <class_name>:
  869. <attr_name_1>: <type>
  870. <attr_name_2>: <type> = <default_value>
  871. <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
  872. ```
  873. * **Objects can be made sortable with `'order=True'` or immutable and hashable with `'frozen=True'`.**
  874. * **Function field() is needed because `'<attr_name>: list = []'` would make a list that is shared among all instances.**
  875. * **Default_factory can be any [callable](#callable).**
  876. #### Inline:
  877. ```python
  878. from dataclasses import make_dataclass
  879. <class> = make_dataclass('<class_name>', <list_of_attribute_names>)
  880. ```
  881. ### Slots
  882. **Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.**
  883. ```python
  884. class MyClassWithSlots:
  885. __slots__ = ['a']
  886. def __init__(self):
  887. self.a = 1
  888. ```
  889. ### Copy
  890. ```python
  891. from copy import copy, deepcopy
  892. <object> = copy(<object>)
  893. <object> = deepcopy(<object>)
  894. ```
  895. Duck Types
  896. ----------
  897. **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.**
  898. ### Comparable
  899. * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
  900. * **That means all objects compare not equal by default.**
  901. * **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.**
  902. ```python
  903. class MyComparable:
  904. def __init__(self, a):
  905. self.a = a
  906. def __eq__(self, other):
  907. if isinstance(other, type(self)):
  908. return self.a == other.a
  909. return NotImplemented
  910. ```
  911. ### Hashable
  912. * **Hashable object needs both hash() and eq() methods and its hash value should never change.**
  913. * **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.**
  914. * **That is why Python automatically makes classes unhashable if you only implement eq().**
  915. ```python
  916. class MyHashable:
  917. def __init__(self, a):
  918. self._a = copy.deepcopy(a)
  919. @property
  920. def a(self):
  921. return self._a
  922. def __eq__(self, other):
  923. if isinstance(other, type(self)):
  924. return self.a == other.a
  925. return NotImplemented
  926. def __hash__(self):
  927. return hash(self.a)
  928. ```
  929. ### Sortable
  930. * **With 'total_ordering' decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.**
  931. ```python
  932. from functools import total_ordering
  933. @total_ordering
  934. class MySortable:
  935. def __init__(self, a):
  936. self.a = a
  937. def __eq__(self, other):
  938. if isinstance(other, type(self)):
  939. return self.a == other.a
  940. return NotImplemented
  941. def __lt__(self, other):
  942. if isinstance(other, type(self)):
  943. return self.a < other.a
  944. return NotImplemented
  945. ```
  946. ### Iterator
  947. * **Next() should return next item or raise StopIteration.**
  948. * **Iter() should return 'self'.**
  949. ```python
  950. class Counter:
  951. def __init__(self):
  952. self.i = 0
  953. def __next__(self):
  954. self.i += 1
  955. return self.i
  956. def __iter__(self):
  957. return self
  958. ```
  959. ```python
  960. >>> counter = Counter()
  961. >>> next(counter), next(counter), next(counter)
  962. (1, 2, 3)
  963. ```
  964. ### Callable
  965. * **All functions and classes have a call() method, hence are callable.**
  966. * **When this cheatsheet uses `'<function>'` for an argument, it actually means `'<callable>'`.**
  967. ```python
  968. class Counter:
  969. def __init__(self):
  970. self.i = 0
  971. def __call__(self):
  972. self.i += 1
  973. return self.i
  974. ```
  975. ```python
  976. >>> counter = Counter()
  977. >>> counter(), counter(), counter()
  978. (1, 2, 3)
  979. ```
  980. ### Context Manager
  981. * **Enter() should lock the resources and return an object.**
  982. * **Exit() should release the resources.**
  983. ```python
  984. class MyOpen():
  985. def __init__(self, filename):
  986. self.filename = filename
  987. def __enter__(self):
  988. self.file = open(self.filename)
  989. return self.file
  990. def __exit__(self, *args):
  991. self.file.close()
  992. ```
  993. ```python
  994. >>> with open('test.txt', 'w') as file:
  995. ... file.write('Hello World!')
  996. >>> with MyOpen('test.txt') as file:
  997. ... print(file.read())
  998. Hello World!
  999. ```
  1000. #### List of covered context managers:
  1001. ```python
  1002. with open('<path>') as file: ...
  1003. with wave.open('<path>') as wave_file: ...
  1004. with memoryview(<bytes/bytearray/array>) as view: ...
  1005. with concurrent.futures.ThreadPoolExecutor() as executor: ...
  1006. db = sqlite3.connect('<path>'); with db: ...
  1007. lock = threading.RLock(); with lock: ...
  1008. ```
  1009. Iterable Duck Types
  1010. -------------------
  1011. ### Iterable
  1012. * **Only required method is iter(). It should return an iterator of object's items.**
  1013. * **Contains() automatically works on any object that has iter() defined.**
  1014. ```python
  1015. class MyIterable:
  1016. def __init__(self, a):
  1017. self.a = a
  1018. def __iter__(self):
  1019. for el in self.a:
  1020. yield el
  1021. ```
  1022. ```python
  1023. >>> z = MyIterable([1, 2, 3])
  1024. >>> iter(z)
  1025. <generator object MyIterable.__iter__ at 0x1026c18b8>
  1026. >>> 1 in z
  1027. True
  1028. ```
  1029. ### Collection
  1030. * **Only required methods are iter() and len().**
  1031. * **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
  1032. * **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.**
  1033. ```python
  1034. class MyCollection:
  1035. def __init__(self, a):
  1036. self.a = a
  1037. def __iter__(self):
  1038. return iter(self.a)
  1039. def __contains__(self, el):
  1040. return el in self.a
  1041. def __len__(self):
  1042. return len(self.a)
  1043. ```
  1044. ### Sequence
  1045. * **Only required methods are len() and getitem().**
  1046. * **Getitem() should return an item at index or raise IndexError.**
  1047. * **Iter() and contains() automatically work on any object that has getitem() defined.**
  1048. * **Reversed() automatically works on any object that has getitem() and len() defined.**
  1049. ```python
  1050. class MySequence:
  1051. def __init__(self, a):
  1052. self.a = a
  1053. def __iter__(self):
  1054. return iter(self.a)
  1055. def __contains__(self, el):
  1056. return el in self.a
  1057. def __len__(self):
  1058. return len(self.a)
  1059. def __getitem__(self, i):
  1060. return self.a[i]
  1061. def __reversed__(self):
  1062. return reversed(self.a)
  1063. ```
  1064. ### Collections.abc.Sequence
  1065. * **It's a richer interface than the basic sequence.**
  1066. * **Extending it generates iter(), contains(), reversed(), index(), and count().**
  1067. * **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, collections.abc.Sequence)'` would return False even if MySequence had all the methods defined.**
  1068. ```python
  1069. class MyAbcSequence(collections.abc.Sequence):
  1070. def __init__(self, a):
  1071. self.a = a
  1072. def __len__(self):
  1073. return len(self.a)
  1074. def __getitem__(self, i):
  1075. return self.a[i]
  1076. ```
  1077. #### Table of required and available special methods:
  1078. ```text
  1079. +------------+----------+------------+----------+--------------+
  1080. | | Iterable | Collection | Sequence | abc.Sequence |
  1081. +------------+----------+------------+----------+--------------+
  1082. | iter() | REQ | REQ | yes | yes |
  1083. | contains() | yes | yes | yes | yes |
  1084. | len() | | REQ | REQ | REQ |
  1085. | getitem() | | | REQ | REQ |
  1086. | reversed() | | | yes | yes |
  1087. | index() | | | | yes |
  1088. | count() | | | | yes |
  1089. +------------+----------+------------+----------+--------------+
  1090. ```
  1091. * **Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.**
  1092. * **Names of their required methods are stored in `'<abc>.__abstractmethods__'`.**
  1093. Enum
  1094. ----
  1095. ```python
  1096. from enum import Enum, auto
  1097. class <enum_name>(Enum):
  1098. <member_name_1> = <value_1>
  1099. <member_name_2> = <value_2_a>, <value_2_b>
  1100. <member_name_3> = auto()
  1101. @classmethod
  1102. def get_member_names(cls):
  1103. return [a.name for a in cls.__members__.values()]
  1104. ```
  1105. * **If there are no numeric values before auto(), it returns 1.**
  1106. * **Otherwise it returns an increment of last numeric value.**
  1107. ```python
  1108. <member> = <enum>.<member_name> # Returns a member.
  1109. <member> = <enum>['<member_name>'] # Returns a member or raises KeyError.
  1110. <member> = <enum>(<value>) # Returns a member or raises ValueError.
  1111. name = <member>.name
  1112. value = <member>.value
  1113. ```
  1114. ```python
  1115. list_of_members = list(<enum>)
  1116. member_names = [a.name for a in <enum>]
  1117. member_values = [a.value for a in <enum>]
  1118. random_member = random.choice(list(<enum>))
  1119. ```
  1120. ### Inline
  1121. ```python
  1122. Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
  1123. Cutlery = Enum('Cutlery', 'fork knife spoon')
  1124. Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
  1125. ```
  1126. #### Functions can not be values, so they must be wrapped:
  1127. ```python
  1128. from functools import partial
  1129. LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
  1130. 'OR' : partial(lambda l, r: l or r)})
  1131. ```
  1132. * **Another solution in this particular case, is to use `'and_'` and `'or_'` functions from module [operator](#operator).**
  1133. Exceptions
  1134. ----------
  1135. ### Basic Example
  1136. ```python
  1137. try:
  1138. <code>
  1139. except <exception>:
  1140. <code>
  1141. ```
  1142. ### Complex Example
  1143. ```python
  1144. try:
  1145. <code_1>
  1146. except <exception_a>:
  1147. <code_2_a>
  1148. except <exception_b>:
  1149. <code_2_b>
  1150. else:
  1151. <code_2_c>
  1152. finally:
  1153. <code_3>
  1154. ```
  1155. ### Catching Exceptions
  1156. ```python
  1157. except <exception>:
  1158. except <exception> as <name>:
  1159. except (<exception>, ...):
  1160. except (<exception>, ...) as <name>:
  1161. ```
  1162. * **Also catches subclasses of the exception.**
  1163. ### Raising Exceptions
  1164. ```python
  1165. raise <exception>
  1166. raise <exception>()
  1167. raise <exception>(<el>)
  1168. raise <exception>(<el>, ...)
  1169. ```
  1170. #### Useful built-in exceptions:
  1171. ```python
  1172. raise ValueError('Argument is of right type but inappropriate value!')
  1173. raise TypeError('Argument is of wrong type!')
  1174. raise RuntimeError('None of above!')
  1175. ```
  1176. #### Re-raising caught exception:
  1177. ```python
  1178. except <exception>:
  1179. <code>
  1180. raise
  1181. ```
  1182. ### Common Built-in Exceptions
  1183. ```text
  1184. BaseException
  1185. +-- SystemExit # Raised by the sys.exit() function.
  1186. +-- KeyboardInterrupt # Raised when the user hits the interrupt key.
  1187. +-- Exception # User-defined exceptions should be derived from this class.
  1188. +-- StopIteration # Raised by next() when run on an empty iterator.
  1189. +-- ArithmeticError # Base class for arithmetic errors.
  1190. | +-- ZeroDivisionError # Raised when dividing by zero.
  1191. +-- AttributeError # Raised when an attribute is missing.
  1192. +-- EOFError # Raised by input() when it hits end-of-file condition.
  1193. +-- LookupError # Raised when a look-up on a sequence or dict fails.
  1194. | +-- IndexError # Raised when a sequence index is out of range.
  1195. | +-- KeyError # Raised when a dictionary key is not found.
  1196. +-- NameError # Raised when a variable name is not found.
  1197. +-- OSError # Failures such as “file not found” or “disk full”.
  1198. | +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
  1199. +-- RuntimeError # Raised by errors that don't fall in other categories.
  1200. | +-- RecursionError # Raised when the the maximum recursion depth is exceeded.
  1201. +-- TypeError # Raised when an argument is of wrong type.
  1202. +-- ValueError # When an argument is of right type but inappropriate value.
  1203. +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
  1204. ```
  1205. #### Collections and their exceptions:
  1206. ```text
  1207. +-----------+------------+----------+----------+
  1208. | | list | dict | set |
  1209. +-----------+------------+----------+----------+
  1210. | getitem() | IndexError | KeyError | |
  1211. | pop() | IndexError | KeyError | KeyError |
  1212. | remove() | ValueError | | KeyError |
  1213. | index() | ValueError | | |
  1214. +-----------+------------+----------+----------+
  1215. ```
  1216. ### User-defined Exceptions
  1217. ```python
  1218. class MyError(Exception):
  1219. pass
  1220. class MyInputError(MyError):
  1221. pass
  1222. ```
  1223. Print
  1224. -----
  1225. ```python
  1226. print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  1227. ```
  1228. * **Use `'file=sys.stderr'` for errors.**
  1229. * **Use `'flush=True'` to forcibly flush the stream.**
  1230. ### Pretty Print
  1231. ```python
  1232. from pprint import pprint
  1233. pprint(<collection>, width=80, depth=None)
  1234. ```
  1235. * **Levels deeper than 'depth' get replaced by '...'.**
  1236. Input
  1237. -----
  1238. * **Reads a line from user input or pipe if present.**
  1239. * **Trailing newline gets stripped.**
  1240. * **Prompt string is printed to the standard output before reading input.**
  1241. * **Raises EOFError when user hits EOF or input stream gets exhausted.**
  1242. ```python
  1243. <str> = input(prompt=None)
  1244. ```
  1245. Command Line Arguments
  1246. ----------------------
  1247. ```python
  1248. import sys
  1249. script_name = sys.argv[0]
  1250. arguments = sys.argv[1:]
  1251. ```
  1252. ### Argparse
  1253. ```python
  1254. from argparse import ArgumentParser, FileType
  1255. p = ArgumentParser(description=<str>)
  1256. p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag
  1257. p.add_argument('-<short_name>', '--<name>', type=<type>) # Option
  1258. p.add_argument('<name>', type=<type>, nargs=1) # First argument
  1259. p.add_argument('<name>', type=<type>, nargs='+') # Remaining arguments
  1260. p.add_argument('<name>', type=<type>, nargs='*') # Optional arguments
  1261. args = p.parse_args() # Exits on error.
  1262. value = args.<name>
  1263. ```
  1264. * **Use `'help=<str>'` to set argument description.**
  1265. * **Use `'default=<el>'` to set the default value.**
  1266. * **Use `'type=FileType(<mode>)'` for files.**
  1267. Open
  1268. ----
  1269. **Opens a file and returns a corresponding file object.**
  1270. ```python
  1271. <file> = open('<path>', mode='r', encoding=None, newline=None)
  1272. ```
  1273. * **`'encoding=None'` means default encoding is used, which is platform dependent. Best practice is to use `'encoding="utf-8"'` whenever possible.**
  1274. * **`'newline=None'` means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.**
  1275. * **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.**
  1276. ### Modes
  1277. * **`'r'` - Read (default).**
  1278. * **`'w'` - Write (truncate).**
  1279. * **`'x'` - Write or fail if the file already exists.**
  1280. * **`'a'` - Append.**
  1281. * **`'w+'` - Read and write (truncate).**
  1282. * **`'r+'` - Read and write from the start.**
  1283. * **`'a+'` - Read and write from the end.**
  1284. * **`'t'` - Text mode (default).**
  1285. * **`'b'` - Binary mode.**
  1286. ### Exceptions
  1287. * **`'FileNotFoundError'` can be risen when reading with `'r'` or `'r+'`.**
  1288. * **`'FileExistsError'` can be risen when writing with `'x'`.**
  1289. * **`'IsADirectoryError'` and `'PermissionError'` can be risen by any.**
  1290. * **`'OSError'` is the parent class of all listed exceptions.**
  1291. ### File
  1292. ```python
  1293. <file>.seek(0) # Moves to the start of the file.
  1294. <file>.seek(offset) # Moves 'offset' chars/bytes from the start.
  1295. <file>.seek(0, 2) # Moves to the end of the file.
  1296. <bin_file>.seek(±offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
  1297. ```
  1298. ```python
  1299. <str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until EOF.
  1300. <str/bytes> = <file>.readline() # Returns a line or empty string on EOF.
  1301. <list> = <file>.readlines() # Returns a list of remaining lines.
  1302. <str/bytes> = next(<file>) # Returns a line using buffer. Do not mix.
  1303. ```
  1304. ```python
  1305. <file>.write(<str/bytes>) # Writes a string or bytes object.
  1306. <file>.writelines(<coll.>) # Writes a coll. of strings or bytes objects.
  1307. <file>.flush() # Flushes write buffer.
  1308. ```
  1309. * **Methods do not add or strip trailing newlines, even writelines().**
  1310. ### Read Text from File
  1311. ```python
  1312. def read_file(filename):
  1313. with open(filename, encoding='utf-8') as file:
  1314. return file.readlines()
  1315. ```
  1316. ### Write Text to File
  1317. ```python
  1318. def write_to_file(filename, text):
  1319. with open(filename, 'w', encoding='utf-8') as file:
  1320. file.write(text)
  1321. ```
  1322. Path
  1323. ----
  1324. ```python
  1325. from os import path, listdir
  1326. from glob import glob
  1327. ```
  1328. ```python
  1329. <bool> = path.exists('<path>')
  1330. <bool> = path.isfile('<path>')
  1331. <bool> = path.isdir('<path>')
  1332. ```
  1333. ```python
  1334. <list> = listdir('<path>') # List of filenames located at path.
  1335. <list> = glob('<pattern>') # Filenames matching the wildcard pattern.
  1336. ```
  1337. ### Pathlib
  1338. ```python
  1339. from pathlib import Path
  1340. ```
  1341. ```python
  1342. cwd = Path()
  1343. <Path> = Path('<path>' [, '<path>', <Path>, ...])
  1344. <Path> = <Path> / '<dir>' / '<file>'
  1345. ```
  1346. ```python
  1347. <bool> = <Path>.exists()
  1348. <bool> = <Path>.is_file()
  1349. <bool> = <Path>.is_dir()
  1350. ```
  1351. ```python
  1352. <iter> = <Path>.iterdir() # Returns dir contents as Path objects.
  1353. <iter> = <Path>.glob('<pattern>') # Returns Paths matching the wildcard pattern.
  1354. ```
  1355. ```python
  1356. <str> = str(<Path>) # Path as a string.
  1357. <str> = <Path>.name # Final component.
  1358. <str> = <Path>.stem # Final component without extension.
  1359. <str> = <Path>.suffix # Final component's extension.
  1360. <tup.> = <Path>.parts # All components as strings.
  1361. ```
  1362. ```python
  1363. <Path> = <Path>.resolve() # Returns absolute path without symlinks.
  1364. <Path> = <Path>.parent # Returns path without final component.
  1365. <file> = open(<Path>) # Opens the file and returns a file object.
  1366. ```
  1367. OS Commands
  1368. -----------
  1369. ### Files and Directories
  1370. * **Paths can be either strings, Paths, or DirEntry objects.**
  1371. * **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).**
  1372. ```python
  1373. import os, shutil
  1374. ```
  1375. ```python
  1376. os.chdir(<path>) # Changes current working directory.
  1377. os.mkdir(<path>, mode=0o777) # Creates a directory.
  1378. ```
  1379. ```python
  1380. os.rename(from, to) # Renames the file or directory.
  1381. os.replace(from, to) # Same, but overwrites 'to' if it exists.
  1382. ```
  1383. ```python
  1384. os.remove(<path>) # Deletes the file.
  1385. os.rmdir(<path>) # Deletes empty directory.
  1386. shutil.rmtree(<path>) # Deletes the entire directory tree.
  1387. ```
  1388. ```python
  1389. shutil.copy(from, to) # Copies the file.
  1390. shutil.copytree(from, to) # Copies the entire directory tree.
  1391. ```
  1392. ```python
  1393. <str> = os.getcwd() # Returns the current working directory.
  1394. <iter> = os.scandir(path='.') # Returns os.DirEntry objects located at path.
  1395. ```
  1396. #### DirEntry:
  1397. ```python
  1398. <bool> = <DirEntry>.is_file()
  1399. <bool> = <DirEntry>.is_dir()
  1400. ```
  1401. ```python
  1402. <str> = <DirEntry>.path # Path as a string.
  1403. <str> = <DirEntry>.name # Final component.
  1404. ```
  1405. ```python
  1406. <Path> = Path(<DirEntry>) # Path object.
  1407. <file> = open(<DirEntry>) # File object.
  1408. ```
  1409. ### Shell Commands
  1410. ```python
  1411. import os
  1412. <str> = os.popen('<shell_command>').read()
  1413. ```
  1414. #### Using subprocess:
  1415. ```python
  1416. >>> import subprocess, shlex
  1417. >>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE)
  1418. >>> a.stdout
  1419. b'.\n..\nfile1.txt\nfile2.txt\n'
  1420. >>> a.returncode
  1421. 0
  1422. ```
  1423. JSON
  1424. ----
  1425. ```python
  1426. import json
  1427. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  1428. <object> = json.loads(<str>)
  1429. ```
  1430. ### Read Object from JSON File
  1431. ```python
  1432. def read_json_file(filename):
  1433. with open(filename, encoding='utf-8') as file:
  1434. return json.load(file)
  1435. ```
  1436. ### Write Object to JSON File
  1437. ```python
  1438. def write_to_json_file(filename, an_object):
  1439. with open(filename, 'w', encoding='utf-8') as file:
  1440. json.dump(an_object, file, ensure_ascii=False, indent=2)
  1441. ```
  1442. Pickle
  1443. ------
  1444. ```python
  1445. import pickle
  1446. <bytes> = pickle.dumps(<object>)
  1447. <object> = pickle.loads(<bytes>)
  1448. ```
  1449. ### Read Object from File
  1450. ```python
  1451. def read_pickle_file(filename):
  1452. with open(filename, 'rb') as file:
  1453. return pickle.load(file)
  1454. ```
  1455. ### Write Object to File
  1456. ```python
  1457. def write_to_pickle_file(filename, an_object):
  1458. with open(filename, 'wb') as file:
  1459. pickle.dump(an_object, file)
  1460. ```
  1461. CSV
  1462. ---
  1463. **Text file format for storing spreadsheets.**
  1464. ```python
  1465. import csv
  1466. ```
  1467. ### Read
  1468. ```python
  1469. <reader> = csv.reader(<file>, dialect='excel', delimiter=',')
  1470. <list> = next(<reader>) # Returns next row as a list of strings.
  1471. <list> = list(<reader>) # Returns list of remaining rows.
  1472. ```
  1473. * **File must be opened with `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!**
  1474. ### Write
  1475. ```python
  1476. <writer> = csv.writer(<file>, dialect='excel', delimiter=',')
  1477. <writer>.writerow(<collection>) # Encodes objects using `str(<el>)`.
  1478. <writer>.writerows(<coll_of_coll>) # Appends multiple rows.
  1479. ```
  1480. * **File must be opened with `'newline=""'` argument, or an extra '\r' will be added on platforms that use '\r\n' linendings!**
  1481. ### Parameters
  1482. * **`'dialect'` - Master parameter that sets the default values.**
  1483. * **`'delimiter'` - A one-character string used to separate fields.**
  1484. * **`'quotechar'` - Character for quoting fields that contain special characters.**
  1485. * **`'doublequote'` - Whether quotechars inside fields get doubled or escaped.**
  1486. * **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped.**
  1487. * **`'lineterminator'` - How does writer terminate lines.**
  1488. * **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.**
  1489. * **`'escapechar'` - Character for escaping 'quotechar' if 'doublequote' is false.**
  1490. ### Dialects
  1491. ```text
  1492. +------------------+-----------+-----------+--------------+
  1493. | | excel | excel_tab | unix_dialect |
  1494. +------------------+-----------+-----------+--------------+
  1495. | delimiter | ',' | '\t' | ',' |
  1496. | quotechar | '"' | '"' | '"' |
  1497. | doublequote | True | True | True |
  1498. | skipinitialspace | False | False | False |
  1499. | lineterminator | '\r\n' | '\r\n' | '\n' |
  1500. | quoting | 0 | 0 | 1 |
  1501. | escapechar | None | None | None |
  1502. +------------------+-----------+-----------+--------------+
  1503. ```
  1504. ### Read Rows from CSV File
  1505. ```python
  1506. def read_csv_file(filename):
  1507. with open(filename, encoding='utf-8', newline='') as file:
  1508. return list(csv.reader(file))
  1509. ```
  1510. ### Write Rows to CSV File
  1511. ```python
  1512. def write_to_csv_file(filename, rows):
  1513. with open(filename, 'w', encoding='utf-8', newline='') as file:
  1514. writer = csv.writer(file)
  1515. writer.writerows(rows)
  1516. ```
  1517. SQLite
  1518. ------
  1519. **Server-less database engine that stores each database into separate file.**
  1520. ```python
  1521. import sqlite3
  1522. db = sqlite3.connect('<path>') # Also ':memory:'.
  1523. ...
  1524. db.close()
  1525. ```
  1526. * **New database will be created if path doesn't exist.**
  1527. ### Read
  1528. ```python
  1529. <cursor> = db.execute('<query>') # Can raise sqlite3.OperationalError.
  1530. <tuple> = <cursor>.fetchone() # Returns next row. Also next(<cursor>).
  1531. <list> = <cursor>.fetchall() # Returns remaining rows.
  1532. ```
  1533. * **Returned values can be of type str, int, float, bytes or None.**
  1534. ### Write
  1535. ```python
  1536. db.execute('<query>')
  1537. db.commit()
  1538. ```
  1539. #### Or:
  1540. ```python
  1541. with db:
  1542. db.execute('<query>')
  1543. ```
  1544. ### Placeholders
  1545. ```python
  1546. db.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
  1547. db.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
  1548. db.executemany('<query>', <coll_of_above>) # Runs execute() many times.
  1549. ```
  1550. * **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.**
  1551. * **Bools will be stored and returned as ints and dates as ISO formatted strings.**
  1552. ### Example
  1553. ```python
  1554. >>> db = sqlite3.connect('test.db')
  1555. >>> db.execute('create table t (a, b, c)')
  1556. >>> db.execute('insert into t values (1, 2, 3)')
  1557. >>> db.execute('select * from t').fetchall()
  1558. [(1, 2, 3)]
  1559. ```
  1560. * **In this example values are not actually saved because `'db.commit()'` was omitted.**
  1561. ### MySQL
  1562. **Has a very similar interface, with differences listed below.**
  1563. ```python
  1564. # $ pip3 install mysql-connector
  1565. from mysql import connector
  1566. db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>)
  1567. <cursor> = db.cursor()
  1568. <cursor>.execute('<query>') # Only cursor has execute method.
  1569. <cursor>.execute('<query>', <list/tuple>) # Replaces '%s's in query with values.
  1570. <cursor>.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.
  1571. ```
  1572. Bytes
  1573. -----
  1574. **Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.**
  1575. ```python
  1576. <bytes> = b'<str>' # Only accepts ASCII characters and \x00 - \xff.
  1577. <int> = <bytes>[<index>] # Returns int in range from 0 to 255.
  1578. <bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
  1579. <bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes object as separator.
  1580. ```
  1581. ### Encode
  1582. ```python
  1583. <bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
  1584. <bytes> = bytes(<str>, 'utf-8') # Or: <str>.encode('utf-8')
  1585. <bytes> = <int>.to_bytes(n_bytes, byteorder='big|little', signed=False)
  1586. <bytes> = bytes.fromhex('<hex>')
  1587. ```
  1588. ### Decode
  1589. ```python
  1590. <list> = list(<bytes>) # Returns ints in range from 0 to 255.
  1591. <str> = str(<bytes>, 'utf-8') # Or: <bytes>.decode('utf-8')
  1592. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  1593. '<hex>' = <bytes>.hex()
  1594. ```
  1595. ### Read Bytes from File
  1596. ```python
  1597. def read_bytes(filename):
  1598. with open(filename, 'rb') as file:
  1599. return file.read()
  1600. ```
  1601. ### Write Bytes to File
  1602. ```python
  1603. def write_bytes(filename, bytes_obj):
  1604. with open(filename, 'wb') as file:
  1605. file.write(bytes_obj)
  1606. ```
  1607. Struct
  1608. ------
  1609. * **Module that performs conversions between a sequence of numbers and a bytes object.**
  1610. * **Machine’s native type sizes and byte order are used by default.**
  1611. ```python
  1612. from struct import pack, unpack, iter_unpack
  1613. <bytes> = pack('<format>', <num_1> [, <num_2>, ...])
  1614. <tuple> = unpack('<format>', <bytes>)
  1615. <tuples> = iter_unpack('<format>', <bytes>)
  1616. ```
  1617. ### Example
  1618. ```python
  1619. >>> pack('>hhl', 1, 2, 3)
  1620. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  1621. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  1622. (1, 2, 3)
  1623. ```
  1624. ### Format
  1625. #### For standard sizes start format string with:
  1626. * **`'='` - native byte order**
  1627. * **`'<'` - little-endian**
  1628. * **`'>'` - big-endian**
  1629. #### Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:
  1630. * **`'x'` - pad byte**
  1631. * **`'b'` - char (1)**
  1632. * **`'h'` - short (2)**
  1633. * **`'i'` - int (4)**
  1634. * **`'l'` - long (4)**
  1635. * **`'q'` - long long (8)**
  1636. #### Floating point types:
  1637. * **`'f'` - float (4)**
  1638. * **`'d'` - double (8)**
  1639. Array
  1640. -----
  1641. **List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.**
  1642. ```python
  1643. from array import array
  1644. <array> = array('<typecode>', <collection>) # Array from coll. of numbers.
  1645. <array> = array('<typecode>', <bytes>) # Array from bytes object.
  1646. <bytes> = <array>.tobytes()
  1647. ```
  1648. Memory View
  1649. -----------
  1650. * **A sequence object that points to the memory of another object.**
  1651. * **Each element can reference a single or multiple consecutive bytes, depending on format.**
  1652. * **Order and number of elements can be changed with slicing.**
  1653. ```python
  1654. <mview> = memoryview(<bytes/bytearray/array>)
  1655. <num> = <mview>[<index>] # Returns an int or a float.
  1656. <mview> = <mview>[<slice>] # Mview with rearranged elements.
  1657. <mview> = <mview>.cast('<typecode>') # Casts a memoryview to a new format.
  1658. <mview>.release() # Releases the object's memory buffer.
  1659. ```
  1660. ```python
  1661. <bin_file>.write(<mview>) # Writes mview to a binary file.
  1662. <bytes> = bytes(<mview>) # Creates a new bytes object.
  1663. <bytes> = <bytes>.join(<coll_of_mviews>) # Joins mviews using bytes object as sep.
  1664. ```
  1665. ```python
  1666. <list> = list(<mview>) # Returns list of ints or floats.
  1667. <str> = str(<mview>, 'utf-8')
  1668. <int> = int.from_bytes(<mview>, byteorder='big|little', signed=False)
  1669. '<hex>' = <mview>.hex()
  1670. ```
  1671. Deque
  1672. -----
  1673. **A thread-safe list with efficient appends and pops from either side. Pronounced "deck".**
  1674. ```python
  1675. from collections import deque
  1676. <deque> = deque(<collection>, maxlen=None)
  1677. ```
  1678. ```python
  1679. <deque>.appendleft(<el>) # Opposite element is dropped if full.
  1680. <el> = <deque>.popleft() # Raises IndexError if empty.
  1681. <deque>.extendleft(<collection>) # Collection gets reversed.
  1682. <deque>.rotate(n=1) # Rotates elements to the right.
  1683. ```
  1684. Threading
  1685. ---------
  1686. * **CPython interpreter can only run a single thread at a time.**
  1687. * **That is why using multiple threads won't result in a faster execution, unless there is an I/O operation in the thread.**
  1688. ```python
  1689. from threading import Thread, RLock
  1690. ```
  1691. ### Thread
  1692. ```python
  1693. thread = Thread(target=<function>, args=(<first_arg>, ))
  1694. thread.start()
  1695. ...
  1696. <bool> = thread.is_alive() # Checks if thread has finished executing.
  1697. thread.join() # Waits for thread to finish.
  1698. ```
  1699. ### Lock
  1700. ```python
  1701. lock = RLock()
  1702. lock.acquire() # Waits for lock to be available.
  1703. ...
  1704. lock.release()
  1705. ```
  1706. #### Or:
  1707. ```python
  1708. lock = RLock()
  1709. with lock:
  1710. ...
  1711. ```
  1712. ### Thread Pool
  1713. ```python
  1714. from concurrent.futures import ThreadPoolExecutor
  1715. with ThreadPoolExecutor(max_workers=None) as executor:
  1716. <iter> = executor.map(lambda x: x + 1, range(3)) # (1, 2, 3)
  1717. <iter> = executor.map(lambda x, y: x + y, 'abc', '123') # ('a1', 'b2', 'c3')
  1718. <Future> = executor.submit(<function> [, <arg_1>, ...])
  1719. ```
  1720. ```python
  1721. <bool> = <Future>.done() # Checks if thread has finished executing.
  1722. <obj> = <Future>.result() # Waits for thread to finish and returns result.
  1723. ```
  1724. ### Queue
  1725. **A thread-safe FIFO queue. For LIFO queue use LifoQueue.**
  1726. ```python
  1727. from queue import Queue
  1728. <Queue> = Queue(maxsize=0)
  1729. ```
  1730. ```python
  1731. <Queue>.put(<el>) # Blocks until queue stops being full.
  1732. <Queue>.put_nowait(<el>) # Raises queue.Full exception if full.
  1733. <el> = <Queue>.get() # Blocks until queue stops being empty.
  1734. <el> = <Queue>.get_nowait() # Raises _queue.Empty exception if empty.
  1735. ```
  1736. Operator
  1737. --------
  1738. ```python
  1739. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
  1740. from operator import eq, ne, lt, le, gt, ge
  1741. from operator import and_, or_, not_
  1742. from operator import itemgetter, attrgetter, methodcaller
  1743. ```
  1744. ```python
  1745. import operator as op
  1746. sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
  1747. sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
  1748. product_of_elems = functools.reduce(op.mul, <collection>)
  1749. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1750. last_el = op.methodcaller('pop')(<list>)
  1751. ```
  1752. Introspection
  1753. -------------
  1754. **Inspecting code at runtime.**
  1755. ### Variables
  1756. ```python
  1757. <list> = dir() # Names of variables in current scope.
  1758. <dict> = locals() # Dict of local variables. Also vars().
  1759. <dict> = globals() # Dict of global variables.
  1760. ```
  1761. ### Attributes
  1762. ```python
  1763. <dict> = vars(<object>)
  1764. <bool> = hasattr(<object>, '<attr_name>')
  1765. value = getattr(<object>, '<attr_name>')
  1766. setattr(<object>, '<attr_name>', value)
  1767. ```
  1768. ### Parameters
  1769. ```python
  1770. from inspect import signature
  1771. <sig> = signature(<function>)
  1772. no_of_params = len(<sig>.parameters)
  1773. param_names = list(<sig>.parameters.keys())
  1774. ```
  1775. Metaprograming
  1776. --------------
  1777. **Code that generates code.**
  1778. ### Type
  1779. **Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.**
  1780. ```python
  1781. <class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
  1782. ```
  1783. ```python
  1784. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1785. >>> z = Z()
  1786. ```
  1787. ### Meta Class
  1788. **Class that creates classes.**
  1789. ```python
  1790. def my_meta_class(name, parents, attrs):
  1791. attrs['a'] = 'abcde'
  1792. return type(name, parents, attrs)
  1793. ```
  1794. #### Or:
  1795. ```python
  1796. class MyMetaClass(type):
  1797. def __new__(cls, name, parents, attrs):
  1798. attrs['a'] = 'abcde'
  1799. return type.__new__(cls, name, parents, attrs)
  1800. ```
  1801. * **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.**
  1802. * **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (MyMetaClass in our case).**
  1803. * **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.**
  1804. ### Metaclass Attribute
  1805. **Right before a class is created it checks if it has a 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().**
  1806. ```python
  1807. class MyClass(metaclass=MyMetaClass):
  1808. b = 12345
  1809. ```
  1810. ```python
  1811. >>> MyClass.a, MyClass.b
  1812. ('abcde', 12345)
  1813. ```
  1814. ### Type Diagram
  1815. ```python
  1816. type(MyClass) == MyMetaClass # MyClass is an instance of MyMetaClass.
  1817. type(MyMetaClass) == type # MyMetaClass is an instance of type.
  1818. ```
  1819. ```text
  1820. +---------+-------------+
  1821. | Classes | Metaclasses |
  1822. +---------+-------------|
  1823. | MyClass > MyMetaClass |
  1824. | | v |
  1825. | object ---> type <+ |
  1826. | | ^ +---+ |
  1827. | str -------+ |
  1828. +---------+-------------+
  1829. ```
  1830. ### Inheritance Diagram
  1831. ```python
  1832. MyClass.__base__ == object # MyClass is a subclass of object.
  1833. MyMetaClass.__base__ == type # MyMetaClass is a subclass of type.
  1834. ```
  1835. ```text
  1836. +---------+-------------+
  1837. | Classes | Metaclasses |
  1838. +---------+-------------|
  1839. | MyClass | MyMetaClass |
  1840. | v | v |
  1841. | object <--- type |
  1842. | ^ | |
  1843. | str | |
  1844. +---------+-------------+
  1845. ```
  1846. Eval
  1847. ----
  1848. ```python
  1849. >>> from ast import literal_eval
  1850. >>> literal_eval('1 + 2')
  1851. 3
  1852. >>> literal_eval('[1, 2, 3]')
  1853. [1, 2, 3]
  1854. >>> literal_eval('abs(1)')
  1855. ValueError: malformed node or string
  1856. ```
  1857. Coroutine
  1858. ---------
  1859. * **Any function that contains a `'(yield)'` expression returns a coroutine.**
  1860. * **Coroutines are similar to iterators, but data needs to be pulled out of an iterator by calling `'next(<iter>)'`, while we push data into the coroutine by calling `'<coroutine>.send(<el>)'`.**
  1861. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1862. ### Helper Decorator
  1863. * **All coroutines must first be "primed" by calling `'next(<coroutine>)'`.**
  1864. * **Remembering to call next() is easy to forget.**
  1865. * **Solved by wrapping functions that return a coroutine with a decorator:**
  1866. ```python
  1867. def coroutine(func):
  1868. def out(*args, **kwargs):
  1869. cr = func(*args, **kwargs)
  1870. next(cr)
  1871. return cr
  1872. return out
  1873. ```
  1874. ### Pipeline Example
  1875. ```python
  1876. def reader(target):
  1877. for i in range(10):
  1878. target.send(i)
  1879. target.close()
  1880. @coroutine
  1881. def adder(target):
  1882. while True:
  1883. value = (yield)
  1884. target.send(value + 100)
  1885. @coroutine
  1886. def printer():
  1887. while True:
  1888. value = (yield)
  1889. print(value)
  1890. reader(adder(printer())) # 100, 101, ..., 109
  1891. ```
  1892. <br>
  1893. Libraries
  1894. =========
  1895. Progress Bar
  1896. ------------
  1897. ```python
  1898. # $ pip3 install tqdm
  1899. from tqdm import tqdm
  1900. from time import sleep
  1901. for el in tqdm([1, 2, 3]):
  1902. sleep(0.2)
  1903. ```
  1904. Plot
  1905. ----
  1906. ```python
  1907. # $ pip3 install matplotlib
  1908. from matplotlib import pyplot
  1909. pyplot.plot(<y_data> [, label=<str>])
  1910. pyplot.plot(<x_data>, <y_data>)
  1911. pyplot.legend() # Adds a legend.
  1912. pyplot.savefig(<filename>) # Saves figure.
  1913. pyplot.show() # Displays figure.
  1914. pyplot.clf() # Clears figure.
  1915. ```
  1916. Table
  1917. -----
  1918. #### Prints a CSV file as an ASCII table:
  1919. ```python
  1920. # $ pip3 install tabulate
  1921. import csv, tabulate
  1922. with open('test.csv', encoding='utf-8', newline='') as file:
  1923. rows = csv.reader(file)
  1924. header = [a.title() for a in next(rows)]
  1925. table = tabulate.tabulate(rows, header)
  1926. print(table)
  1927. ```
  1928. Curses
  1929. ------
  1930. #### Clears the terminal, prints a message and waits for an ESC key press:
  1931. ```python
  1932. from curses import wrapper, curs_set, ascii
  1933. from curses import KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT
  1934. def main():
  1935. wrapper(draw)
  1936. def draw(screen):
  1937. curs_set(0) # Makes cursor invisible.
  1938. screen.nodelay(True) # Makes getch() non-blocking.
  1939. screen.clear()
  1940. screen.addstr(0, 0, 'Press ESC to quit.')
  1941. while screen.getch() != ascii.ESC:
  1942. pass
  1943. def get_border(screen):
  1944. from collections import namedtuple
  1945. P = namedtuple('P', 'x y')
  1946. height, width = screen.getmaxyx()
  1947. return P(width-1, height-1)
  1948. if __name__ == '__main__':
  1949. main()
  1950. ```
  1951. Logging
  1952. -------
  1953. ```python
  1954. # $ pip3 install loguru
  1955. from loguru import logger
  1956. ```
  1957. ```python
  1958. logger.add('debug_{time}.log', colorize=True) # Connects a log file.
  1959. logger.add('error_{time}.log', level='ERROR') # Another file for errors or higher.
  1960. logger.<level>('A logging message.')
  1961. ```
  1962. * **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.**
  1963. ### Exceptions
  1964. **Exception description, stack trace and values of variables are appended automatically.**
  1965. ```python
  1966. try:
  1967. ...
  1968. except <exception>:
  1969. logger.exception('An error happened.')
  1970. ```
  1971. ### Rotation
  1972. **Argument that sets a condition when a new log file is created.**
  1973. ```python
  1974. rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
  1975. ```
  1976. * **`'<int>'` - Max file size in bytes.**
  1977. * **`'<timedelta>'` - Max age of a file.**
  1978. * **`'<time>'` - Time of day.**
  1979. * **`'<str>'` - Any of above as a string: `'100 MB'`, `'1 month'`, `'monday at 12:00'`, ...**
  1980. ### Retention
  1981. **Sets a condition which old log files get deleted.**
  1982. ```python
  1983. retention=<int>|<datetime.timedelta>|<str>
  1984. ```
  1985. * **`'<int>'` - Max number of files.**
  1986. * **`'<timedelta>'` - Max age of a file.**
  1987. * **`'<str>'` - Max age as a string: `'1 week, 3 days'`, `'2 months'`, ...**
  1988. Scraping
  1989. --------
  1990. #### Scrapes Python's URL, version number and logo from Wikipedia page:
  1991. ```python
  1992. # $ pip3 install requests beautifulsoup4
  1993. import requests
  1994. from bs4 import BeautifulSoup
  1995. url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1996. html = requests.get(url).text
  1997. doc = BeautifulSoup(html, 'html.parser')
  1998. table = doc.find('table', class_='infobox vevent')
  1999. rows = table.find_all('tr')
  2000. link = rows[11].find('a')['href']
  2001. ver = rows[6].find('div').text.split()[0]
  2002. url_i = rows[0].find('img')['src']
  2003. image = requests.get(f'https:{url_i}').content
  2004. with open('test.png', 'wb') as file:
  2005. file.write(image)
  2006. print(link, ver)
  2007. ```
  2008. Web
  2009. ---
  2010. ```python
  2011. # $ pip3 install bottle
  2012. from bottle import run, route, post, template, request, response
  2013. import json
  2014. ```
  2015. ### Run
  2016. ```python
  2017. run(host='localhost', port=8080)
  2018. run(host='0.0.0.0', port=80, server='cherrypy')
  2019. ```
  2020. ### Static Request
  2021. ```python
  2022. @route('/img/<image>')
  2023. def send_image(image):
  2024. return static_file(image, 'images/', mimetype='image/png')
  2025. ```
  2026. ### Dynamic Request
  2027. ```python
  2028. @route('/<sport>')
  2029. def send_page(sport):
  2030. return template('<h1>{{title}}</h1>', title=sport)
  2031. ```
  2032. ### REST Request
  2033. ```python
  2034. @post('/odds/<sport>')
  2035. def odds_handler(sport):
  2036. team = request.forms.get('team')
  2037. home_odds, away_odds = 2.44, 3.29
  2038. response.headers['Content-Type'] = 'application/json'
  2039. response.headers['Cache-Control'] = 'no-cache'
  2040. return json.dumps([team, home_odds, away_odds])
  2041. ```
  2042. #### Test:
  2043. ```python
  2044. # $ pip3 install requests
  2045. >>> import requests
  2046. >>> url = 'http://localhost:8080/odds/football'
  2047. >>> data = {'team': 'arsenal f.c.'}
  2048. >>> response = requests.post(url, data=data)
  2049. >>> response.json()
  2050. ['arsenal f.c.', 2.44, 3.29]
  2051. ```
  2052. Profiling
  2053. ---------
  2054. ### Stopwatch
  2055. ```python
  2056. from time import time
  2057. start_time = time() # Seconds since the Epoch.
  2058. ...
  2059. duration = time() - start_time
  2060. ```
  2061. #### High performance:
  2062. ```python
  2063. from time import perf_counter
  2064. start_time = perf_counter() # Seconds since restart.
  2065. ...
  2066. duration = perf_counter() - start_time
  2067. ```
  2068. ### Timing a Snippet
  2069. ```python
  2070. >>> from timeit import timeit
  2071. >>> timeit('"-".join(str(a) for a in range(100))',
  2072. ... number=10000, globals=globals(), setup='pass')
  2073. 0.34986
  2074. ```
  2075. ### Profiling by Line
  2076. ```python
  2077. # $ pip3 install line_profiler memory_profiler
  2078. @profile
  2079. def main():
  2080. a = [*range(10000)]
  2081. b = {*range(10000)}
  2082. main()
  2083. ```
  2084. ```text
  2085. $ kernprof -lv test.py
  2086. Line # Hits Time Per Hit % Time Line Contents
  2087. =======================================================
  2088. 1 @profile
  2089. 2 def main():
  2090. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  2091. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  2092. ```
  2093. ```text
  2094. $ python3 -m memory_profiler test.py
  2095. Line # Mem usage Increment Line Contents
  2096. =======================================================
  2097. 1 35.387 MiB 35.387 MiB @profile
  2098. 2 def main():
  2099. 3 35.734 MiB 0.348 MiB a = [*range(10000)]
  2100. 4 36.160 MiB 0.426 MiB b = {*range(10000)}
  2101. ```
  2102. ### Call Graph
  2103. #### Generates a PNG image of a call graph with highlighted bottlenecks:
  2104. ```python
  2105. # $ pip3 install pycallgraph
  2106. from pycallgraph import output, PyCallGraph
  2107. from datetime import datetime
  2108. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  2109. filename = f'profile-{time_str}.png'
  2110. drawer = output.GraphvizOutput(output_file=filename)
  2111. with PyCallGraph(drawer):
  2112. <code_to_be_profiled>
  2113. ```
  2114. NumPy
  2115. -----
  2116. **Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.**
  2117. ```python
  2118. # $ pip3 install numpy
  2119. import numpy as np
  2120. ```
  2121. ```python
  2122. <array> = np.array(<list>)
  2123. <array> = np.arange(from_inclusive, to_exclusive, ±step_size)
  2124. <array> = np.ones(<shape>)
  2125. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  2126. ```
  2127. ```python
  2128. <array>.shape = <shape>
  2129. <view> = <array>.reshape(<shape>)
  2130. <view> = np.broadcast_to(<array>, <shape>)
  2131. ```
  2132. ```python
  2133. <array> = <array>.sum(axis)
  2134. indexes = <array>.argmin(axis)
  2135. ```
  2136. * **Shape is a tuple of dimension sizes.**
  2137. * **Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.**
  2138. ### Indexing
  2139. ```bash
  2140. <el> = <2d_array>[0, 0] # First element.
  2141. <1d_view> = <2d_array>[0] # First row.
  2142. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  2143. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  2144. ```
  2145. ```bash
  2146. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  2147. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  2148. ```
  2149. ```bash
  2150. <2d_bools> = <2d_array> > 0
  2151. <1d_array> = <2d_array>[<2d_bools>]
  2152. ```
  2153. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  2154. ### Broadcasting
  2155. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  2156. ```python
  2157. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  2158. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  2159. ```
  2160. #### 1. If array shapes differ in length, left-pad the shorter shape with ones:
  2161. ```python
  2162. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  2163. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  2164. ```
  2165. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  2166. ```python
  2167. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  2168. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  2169. ```
  2170. #### 3. If neither non-matching dimension has size 1, rise an error.
  2171. ### Example
  2172. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  2173. ```python
  2174. >>> points = np.array([0.1, 0.6, 0.8])
  2175. [ 0.1, 0.6, 0.8]
  2176. >>> wrapped_points = points.reshape(3, 1)
  2177. [[ 0.1],
  2178. [ 0.6],
  2179. [ 0.8]]
  2180. >>> distances = wrapped_points - points
  2181. [[ 0. , -0.5, -0.7],
  2182. [ 0.5, 0. , -0.2],
  2183. [ 0.7, 0.2, 0. ]]
  2184. >>> distances = np.abs(distances)
  2185. [[ 0. , 0.5, 0.7],
  2186. [ 0.5, 0. , 0.2],
  2187. [ 0.7, 0.2, 0. ]]
  2188. >>> i = np.arange(3)
  2189. [0, 1, 2]
  2190. >>> distances[i, i] = np.inf
  2191. [[ inf, 0.5, 0.7],
  2192. [ 0.5, inf, 0.2],
  2193. [ 0.7, 0.2, inf]]
  2194. >>> distances.argmin(1)
  2195. [1, 2, 1]
  2196. ```
  2197. Image
  2198. -----
  2199. ```python
  2200. # $ pip3 install pillow
  2201. from PIL import Image
  2202. ```
  2203. ```python
  2204. <Image> = Image.new('<mode>', (width, height))
  2205. <Image> = Image.open('<path>')
  2206. <Image> = <Image>.convert('<mode>')
  2207. <Image>.save('<path>')
  2208. <Image>.show()
  2209. ```
  2210. ```python
  2211. <tuple/int> = <Image>.getpixel((x, y)) # Returns a pixel.
  2212. <Image>.putpixel((x, y), <tuple/int>) # Writes a pixel to image.
  2213. <ImagingCore> = <Image>.getdata() # Returns a sequence of pixels.
  2214. <Image>.putdata(<list/tuple/ImagingCore>) # Writes a sequence of pixels.
  2215. <Image>.paste(<Image>, (x, y)) # Writes an image to image.
  2216. ```
  2217. ### Modes
  2218. * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.**
  2219. * **`'L'` - 8-bit pixels, greyscale.**
  2220. * **`'RGB'` - 3x8-bit pixels, true color.**
  2221. * **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.**
  2222. * **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.**
  2223. ### Examples
  2224. #### Creates a PNG image of a rainbow gradient:
  2225. ```python
  2226. WIDTH, HEIGHT = 100, 100
  2227. size = WIDTH * HEIGHT
  2228. hues = [255 * i/size for i in range(size)]
  2229. img = Image.new('HSV', (WIDTH, HEIGHT))
  2230. img.putdata([(int(h), 255, 255) for h in hues])
  2231. img.convert('RGB').save('test.png')
  2232. ```
  2233. #### Adds noise to a PNG image:
  2234. ```python
  2235. from random import randint
  2236. add_noise = lambda value: max(0, min(255, value + randint(-20, 20)))
  2237. img = Image.open('test.png').convert('HSV')
  2238. img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
  2239. img.convert('RGB').save('test.png')
  2240. ```
  2241. ### ImageDraw
  2242. ```python
  2243. from PIL import ImageDraw
  2244. ```
  2245. ```python
  2246. <ImageDraw> = ImageDraw.Draw(<Image>)
  2247. <ImageDraw>.point((x, y), fill=None)
  2248. <ImageDraw>.line((x1, y1, x2, y2 [, ...]), fill=None, width=0, joint=None)
  2249. <ImageDraw>.arc((x1, y1, x2, y2), from_deg, to_deg, fill=None, width=0)
  2250. <ImageDraw>.rectangle((x1, y1, x2, y2), fill=None, outline=None, width=0)
  2251. <ImageDraw>.polygon((x1, y1, x2, y2 [, ...]), fill=None, outline=None)
  2252. <ImageDraw>.ellipse((x1, y1, x2, y2), fill=None, outline=None, width=0)
  2253. ```
  2254. * **Use `'fill=<color>'` to set the primary color.**
  2255. * **Use `'outline=<color>'` to set the secondary color.**
  2256. * **Colors can be specified as tuple, int, `'#rrggbb'` string or a color name.**
  2257. Animation
  2258. ---------
  2259. #### Creates a GIF of a bouncing ball:
  2260. ```python
  2261. # $ pip3 install pillow imageio
  2262. from PIL import Image, ImageDraw
  2263. import imageio
  2264. WIDTH, R = 126, 10
  2265. frames = []
  2266. for velocity in range(15):
  2267. y = sum(range(velocity+1))
  2268. frame = Image.new('L', (WIDTH, WIDTH))
  2269. draw = ImageDraw.Draw(frame)
  2270. draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+2*R), fill='white')
  2271. frames.append(frame)
  2272. frames += reversed(frames[1:-1])
  2273. imageio.mimsave('test.gif', frames, duration=0.03)
  2274. ```
  2275. Audio
  2276. -----
  2277. ```python
  2278. import wave
  2279. ```
  2280. ```python
  2281. <Wave_read> = wave.open('<path>', 'rb')
  2282. framerate = <Wave_read>.getframerate() # Number of frames per second.
  2283. nchannels = <Wave_read>.getnchannels() # Number of samples per frame.
  2284. sampwidth = <Wave_read>.getsampwidth() # Sample size in bytes.
  2285. nframes = <Wave_read>.getnframes() # Number of frames.
  2286. <bytes> = <Wave_read>.readframes(nframes) # Returns next 'nframes' frames.
  2287. ```
  2288. ```python
  2289. <Wave_write> = wave.open('<path>', 'wb')
  2290. <Wave_write>.setframerate(<int>) # 44100 for CD, 48000 for video.
  2291. <Wave_write>.setnchannels(<int>) # 1 for mono, 2 for stereo.
  2292. <Wave_write>.setsampwidth(<int>) # 2 for CD quality sound.
  2293. <Wave_write>.writeframes(<bytes>) # Appends frames to file.
  2294. ```
  2295. * **Bytes object contains a sequence of frames, each consisting of one or more samples.**
  2296. * **In stereo signal first sample of a frame belongs to the left channel.**
  2297. * **Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.**
  2298. * **If sample width is one, then the integer should be encoded unsigned.**
  2299. * **For all other sizes the integer should be encoded signed with little-endian byte order.**
  2300. ### Sample Values
  2301. ```text
  2302. +-----------+-------------+------+-------------+
  2303. | sampwidth | min | zero | max |
  2304. +-----------+-------------+------+-------------+
  2305. | 1 | 0 | 128 | 255 |
  2306. | 2 | -32768 | 0 | 32767 |
  2307. | 3 | -8388608 | 0 | 8388607 |
  2308. | 4 | -2147483648 | 0 | 2147483647 |
  2309. +-----------+-------------+------+-------------+
  2310. ```
  2311. ### Read Float Samples from WAV File
  2312. ```python
  2313. def read_wav_file(filename):
  2314. def get_int(a_bytes):
  2315. an_int = int.from_bytes(a_bytes, 'little', signed=width!=1)
  2316. return an_int - 128 * (width == 1)
  2317. with wave.open(filename, 'rb') as file:
  2318. frames = file.readframes(file.getnframes())
  2319. width = file.getsampwidth()
  2320. samples = (frames[i: i + width] for i in range(0, len(frames), width))
  2321. return [get_int(a) / pow(2, width * 8 - 1) for a in samples]
  2322. ```
  2323. ### Write Float Samples to WAV File
  2324. ```python
  2325. def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framerate=44100):
  2326. def get_bytes(a_float):
  2327. a_float = max(-1, min(1 - 2e-16, a_float))
  2328. a_float += sampwidth == 1
  2329. a_float *= pow(2, sampwidth * 8 - 1)
  2330. return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1)
  2331. with wave.open(filename, 'wb') as file:
  2332. file.setnchannels(nchannels)
  2333. file.setsampwidth(sampwidth)
  2334. file.setframerate(framerate)
  2335. file.writeframes(b''.join(get_bytes(a) for a in float_samples))
  2336. ```
  2337. ### Examples
  2338. #### Saves a sine wave to a mono WAV file:
  2339. ```python
  2340. from math import pi, sin
  2341. frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
  2342. write_to_wav_file('test.wav', frames_f)
  2343. ```
  2344. #### Adds noise to a mono WAV file:
  2345. ```python
  2346. from random import random
  2347. add_noise = lambda value: value + (random() - 0.5) * 0.03
  2348. frames_f = (add_noise(a) for a in read_wav_file('test.wav'))
  2349. write_to_wav_file('test.wav', frames_f)
  2350. ```
  2351. Synthesizer
  2352. -----------
  2353. #### Plays Popcorn by Gershon Kingsley:
  2354. ```python
  2355. # $ pip3 install simpleaudio
  2356. import simpleaudio, math, struct
  2357. from itertools import chain, repeat
  2358. F = 44100
  2359. P1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,'
  2360. P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'
  2361. get_pause = lambda seconds: repeat(0, int(seconds * F))
  2362. sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
  2363. get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
  2364. get_hz = lambda key: 8.176 * 2 ** (int(key) / 12)
  2365. parse_note = lambda note: (get_hz(note[:2]), 0.25 if '♪' in note else 0.125)
  2366. get_frames = lambda note: get_wave(*parse_note(note)) if note else get_pause(0.125)
  2367. frames_f = chain.from_iterable(get_frames(n) for n in f'{P1}{P1}{P2}'.split(','))
  2368. frames_b = b''.join(struct.pack('<h', int(f * 30000)) for f in frames_f)
  2369. simpleaudio.play_buffer(frames_b, 1, 2, F)
  2370. ```
  2371. Basic Script Template
  2372. ---------------------
  2373. ```python
  2374. #!/usr/bin/env python3
  2375. #
  2376. # Usage: .py
  2377. #
  2378. from collections import namedtuple
  2379. from dataclasses import make_dataclass
  2380. from enum import Enum
  2381. from sys import argv
  2382. import re
  2383. def main():
  2384. pass
  2385. ###
  2386. ## UTIL
  2387. #
  2388. def read_file(filename):
  2389. with open(filename, encoding='utf-8') as file:
  2390. return file.readlines()
  2391. if __name__ == '__main__':
  2392. main()
  2393. ```