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.

2828 lines
83 KiB

7 years ago
7 years ago
5 years ago
6 years ago
7 years ago
7 years ago
7 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
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
7 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
7 years ago
7 years ago
7 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
7 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
7 years ago
6 years ago
7 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
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
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
6 years ago
6 years ago
5 years ago
6 years ago
7 years ago
7 years ago
5 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
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
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
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
5 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
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
5 years ago
5 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
5 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
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
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
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
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
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
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
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
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
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
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
5 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
5 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
5 years ago
6 years ago
7 years ago
6 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
7 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
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
7 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
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
  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-d3a72f9.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`](#command-execution)**__.__
  12. **&nbsp;&nbsp;&nbsp;** **5. Data:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`CSV`](#csv)**__,__ **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`MemoryView`](#memory-view)**__,__ **[`Deque`](#deque)**__.__
  13. **&nbsp;&nbsp;&nbsp;** **6. Advanced:** **&nbsp;&nbsp;&nbsp;** **[`Threading`](#threading)**__,__ **[`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 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 space or `'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. ### Slots
  877. **Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.**
  878. ```python
  879. class MyClassWithSlots:
  880. __slots__ = ['a']
  881. def __init__(self):
  882. self.a = 1
  883. ```
  884. ### Copy
  885. ```python
  886. from copy import copy, deepcopy
  887. <object> = copy(<object>)
  888. <object> = deepcopy(<object>)
  889. ```
  890. Duck Types
  891. ----------
  892. **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.**
  893. ### Comparable
  894. * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
  895. * **That means all objects compare not equal by default.**
  896. * **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.**
  897. ```python
  898. class MyComparable:
  899. def __init__(self, a):
  900. self.a = a
  901. def __eq__(self, other):
  902. if isinstance(other, type(self)):
  903. return self.a == other.a
  904. return NotImplemented
  905. ```
  906. ### Hashable
  907. * **Hashable object needs both hash() and eq() methods and its hash value should never change.**
  908. * **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.**
  909. * **That is why Python automatically makes classes unhashable if you only implement eq().**
  910. ```python
  911. class MyHashable:
  912. def __init__(self, a):
  913. self._a = copy.deepcopy(a)
  914. @property
  915. def a(self):
  916. return self._a
  917. def __eq__(self, other):
  918. if isinstance(other, type(self)):
  919. return self.a == other.a
  920. return NotImplemented
  921. def __hash__(self):
  922. return hash(self.a)
  923. ```
  924. ### Sortable
  925. * **With 'total_ordering' decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.**
  926. ```python
  927. from functools import total_ordering
  928. @total_ordering
  929. class MySortable:
  930. def __init__(self, a):
  931. self.a = a
  932. def __eq__(self, other):
  933. if isinstance(other, type(self)):
  934. return self.a == other.a
  935. return NotImplemented
  936. def __lt__(self, other):
  937. if isinstance(other, type(self)):
  938. return self.a < other.a
  939. return NotImplemented
  940. ```
  941. ### Iterator
  942. * **Next() should return next item or raise StopIteration.**
  943. * **Iter() should return 'self'.**
  944. ```python
  945. class Counter:
  946. def __init__(self):
  947. self.i = 0
  948. def __next__(self):
  949. self.i += 1
  950. return self.i
  951. def __iter__(self):
  952. return self
  953. ```
  954. ```python
  955. >>> counter = Counter()
  956. >>> next(counter), next(counter), next(counter)
  957. (1, 2, 3)
  958. ```
  959. ### Callable
  960. * **All functions and classes have a call() method, hence are callable.**
  961. * **When this cheatsheet uses `'<function>'` for an argument, it actually means `'<callable>'`.**
  962. ```python
  963. class Counter:
  964. def __init__(self):
  965. self.i = 0
  966. def __call__(self):
  967. self.i += 1
  968. return self.i
  969. ```
  970. ```python
  971. >>> counter = Counter()
  972. >>> counter(), counter(), counter()
  973. (1, 2, 3)
  974. ```
  975. ### Context Manager
  976. * **Enter() should lock the resources and return an object.**
  977. * **Exit() should release the resources.**
  978. ```python
  979. class MyOpen():
  980. def __init__(self, filename):
  981. self.filename = filename
  982. def __enter__(self):
  983. self.file = open(self.filename)
  984. return self.file
  985. def __exit__(self, *args):
  986. self.file.close()
  987. ```
  988. ```python
  989. >>> with open('test.txt', 'w') as file:
  990. ... file.write('Hello World!')
  991. >>> with MyOpen('test.txt') as file:
  992. ... print(file.read())
  993. Hello World!
  994. ```
  995. #### List of covered context managers:
  996. ```python
  997. with open('<path>') as file: ...
  998. with wave.open('<path>') as wave_file: ...
  999. with memoryview(<bytes/bytearray/array>) as view: ...
  1000. with concurrent.futures.ThreadPoolExecutor() as executor: ...
  1001. db = sqlite3.connect('<path>'); with db: ...
  1002. lock = threading.RLock(); with lock: ...
  1003. ```
  1004. Iterable Duck Types
  1005. -------------------
  1006. ### Iterable
  1007. * **Only required method is iter(). It should return an iterator of object's items.**
  1008. * **Contains() automatically works on any object that has iter() defined.**
  1009. ```python
  1010. class MyIterable:
  1011. def __init__(self, a):
  1012. self.a = a
  1013. def __iter__(self):
  1014. for el in self.a:
  1015. yield el
  1016. ```
  1017. ```python
  1018. >>> z = MyIterable([1, 2, 3])
  1019. >>> iter(z)
  1020. <generator object MyIterable.__iter__ at 0x1026c18b8>
  1021. >>> 1 in z
  1022. True
  1023. ```
  1024. ### Collection
  1025. * **Only required methods are iter() and len().**
  1026. * **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
  1027. * **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.**
  1028. ```python
  1029. class MyCollection:
  1030. def __init__(self, a):
  1031. self.a = a
  1032. def __iter__(self):
  1033. return iter(self.a)
  1034. def __contains__(self, el):
  1035. return el in self.a
  1036. def __len__(self):
  1037. return len(self.a)
  1038. ```
  1039. ### Sequence
  1040. * **Only required methods are len() and getitem().**
  1041. * **Getitem() should return an item at index or raise IndexError.**
  1042. * **Iter() and contains() automatically work on any object that has getitem() defined.**
  1043. * **Reversed() automatically works on any object that has getitem() and len() defined.**
  1044. ```python
  1045. class MySequence:
  1046. def __init__(self, a):
  1047. self.a = a
  1048. def __iter__(self):
  1049. return iter(self.a)
  1050. def __contains__(self, el):
  1051. return el in self.a
  1052. def __len__(self):
  1053. return len(self.a)
  1054. def __getitem__(self, i):
  1055. return self.a[i]
  1056. def __reversed__(self):
  1057. return reversed(self.a)
  1058. ```
  1059. ### Collections.abc.Sequence
  1060. * **It's a richer interface than the basic sequence.**
  1061. * **Extending it generates iter(), contains(), reversed(), index(), and count().**
  1062. * **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.**
  1063. ```python
  1064. class MyAbcSequence(collections.abc.Sequence):
  1065. def __init__(self, a):
  1066. self.a = a
  1067. def __len__(self):
  1068. return len(self.a)
  1069. def __getitem__(self, i):
  1070. return self.a[i]
  1071. ```
  1072. #### Table of required and available special methods:
  1073. ```text
  1074. +------------+----------+------------+----------+--------------+
  1075. | | Iterable | Collection | Sequence | abc.Sequence |
  1076. +------------+----------+------------+----------+--------------+
  1077. | iter() | REQ | REQ | yes | yes |
  1078. | contains() | yes | yes | yes | yes |
  1079. | len() | | REQ | REQ | REQ |
  1080. | getitem() | | | REQ | REQ |
  1081. | reversed() | | | yes | yes |
  1082. | index() | | | | yes |
  1083. | count() | | | | yes |
  1084. +------------+----------+------------+----------+--------------+
  1085. ```
  1086. * **Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping. Required methods: `'<abc>.__abstractmethods__'`.**
  1087. Enum
  1088. ----
  1089. ```python
  1090. from enum import Enum, auto
  1091. class <enum_name>(Enum):
  1092. <member_name_1> = <value_1>
  1093. <member_name_2> = <value_2_a>, <value_2_b>
  1094. <member_name_3> = auto()
  1095. @classmethod
  1096. def get_member_names(cls):
  1097. return [a.name for a in cls.__members__.values()]
  1098. ```
  1099. * **If there are no numeric values before auto(), it returns 1.**
  1100. * **Otherwise it returns an increment of last numeric value.**
  1101. ```python
  1102. <member> = <enum>.<member_name> # Returns a member.
  1103. <member> = <enum>['<member_name>'] # Returns a member or raises KeyError.
  1104. <member> = <enum>(<value>) # Returns a member or raises ValueError.
  1105. name = <member>.name
  1106. value = <member>.value
  1107. ```
  1108. ```python
  1109. list_of_members = list(<enum>)
  1110. member_names = [a.name for a in <enum>]
  1111. member_values = [a.value for a in <enum>]
  1112. random_member = random.choice(list(<enum>))
  1113. ```
  1114. ### Inline
  1115. ```python
  1116. Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
  1117. Cutlery = Enum('Cutlery', 'fork knife spoon')
  1118. Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
  1119. ```
  1120. #### Functions can not be values, so they must be wrapped:
  1121. ```python
  1122. from functools import partial
  1123. LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
  1124. 'OR' : partial(lambda l, r: l or r)})
  1125. ```
  1126. * **Another solution in this particular case, is to use `'and_'` and `'or_'` functions from module [Operator](#operator).**
  1127. Exceptions
  1128. ----------
  1129. ### Basic Example
  1130. ```python
  1131. try:
  1132. <code>
  1133. except <exception>:
  1134. <code>
  1135. ```
  1136. ### Complex Example
  1137. ```python
  1138. try:
  1139. <code_1>
  1140. except <exception_a>:
  1141. <code_2_a>
  1142. except <exception_b>:
  1143. <code_2_b>
  1144. else:
  1145. <code_2_c>
  1146. finally:
  1147. <code_3>
  1148. ```
  1149. ### Catching Exceptions
  1150. ```python
  1151. except <exception>:
  1152. except <exception> as <name>:
  1153. except (<exception>, ...):
  1154. except (<exception>, ...) as <name>:
  1155. ```
  1156. * **Also catches subclasses of the exception.**
  1157. ### Raising Exceptions
  1158. ```python
  1159. raise <exception>
  1160. raise <exception>()
  1161. raise <exception>(<el>)
  1162. raise <exception>(<el>, ...)
  1163. ```
  1164. #### Useful built-in exceptions:
  1165. ```python
  1166. raise ValueError('Argument is of right type but inappropriate value!')
  1167. raise TypeError('Argument is of wrong type!')
  1168. raise RuntimeError('None of above!')
  1169. ```
  1170. #### Re-raising caught exception:
  1171. ```python
  1172. except <exception>:
  1173. <code>
  1174. raise
  1175. ```
  1176. ### Common Built-in Exceptions
  1177. ```text
  1178. BaseException
  1179. +-- SystemExit # Raised by the sys.exit() function.
  1180. +-- KeyboardInterrupt # Raised when the user hits the interrupt key.
  1181. +-- Exception # User-defined exceptions should be derived from this class.
  1182. +-- StopIteration # Raised by next() when run on an empty iterator.
  1183. +-- ArithmeticError # Base class for arithmetic errors.
  1184. | +-- ZeroDivisionError # Raised when dividing by zero.
  1185. +-- AttributeError # Raised when an attribute is missing.
  1186. +-- EOFError # Raised by input() when it hits end-of-file condition.
  1187. +-- LookupError # Raised when a look-up on a sequence or dict fails.
  1188. | +-- IndexError # Raised when a sequence index is out of range.
  1189. | +-- KeyError # Raised when a dictionary key is not found.
  1190. +-- NameError # Raised when a variable name is not found.
  1191. +-- OSError # Failures such as “file not found” or “disk full”.
  1192. | +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
  1193. +-- RuntimeError # Raised by errors that don't fall in other categories.
  1194. | +-- RecursionError # Raised when the the maximum recursion depth is exceeded.
  1195. +-- TypeError # Raised when an argument is of wrong type.
  1196. +-- ValueError # When an argument is of right type but inappropriate value.
  1197. +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
  1198. ```
  1199. #### Collections and their exceptions:
  1200. ```text
  1201. +-----------+------------+----------+----------+
  1202. | | list | dict | set |
  1203. +-----------+------------+----------+----------+
  1204. | getitem() | IndexError | KeyError | |
  1205. | pop() | IndexError | KeyError | KeyError |
  1206. | remove() | ValueError | | KeyError |
  1207. | index() | ValueError | | |
  1208. +-----------+------------+----------+----------+
  1209. ```
  1210. ### User-defined Exceptions
  1211. ```python
  1212. class MyError(Exception):
  1213. pass
  1214. class MyInputError(MyError):
  1215. pass
  1216. ```
  1217. Print
  1218. -----
  1219. ```python
  1220. print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  1221. ```
  1222. * **Use `'file=sys.stderr'` for errors.**
  1223. * **Use `'flush=True'` to forcibly flush the stream.**
  1224. ### Pretty Print
  1225. ```python
  1226. from pprint import pprint
  1227. pprint(<collection>, width=80, depth=None)
  1228. ```
  1229. * **Levels deeper than 'depth' get replaced by '...'.**
  1230. Input
  1231. -----
  1232. * **Reads a line from user input or pipe if present.**
  1233. * **Trailing newline gets stripped.**
  1234. * **Prompt string is printed to the standard output before reading input.**
  1235. * **Raises EOFError when user hits EOF or input stream gets exhausted.**
  1236. ```python
  1237. <str> = input(prompt=None)
  1238. ```
  1239. Command Line Arguments
  1240. ----------------------
  1241. ```python
  1242. import sys
  1243. script_name = sys.argv[0]
  1244. arguments = sys.argv[1:]
  1245. ```
  1246. ### Argparse
  1247. ```python
  1248. from argparse import ArgumentParser, FileType
  1249. p = ArgumentParser(description=<str>)
  1250. p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag
  1251. p.add_argument('-<short_name>', '--<name>', type=<type>) # Option
  1252. p.add_argument('<name>', type=<type>, nargs=1) # First argument
  1253. p.add_argument('<name>', type=<type>, nargs='+') # Remaining arguments
  1254. p.add_argument('<name>', type=<type>, nargs='*') # Optional arguments
  1255. args = p.parse_args() # Exits on error.
  1256. value = args.<name>
  1257. ```
  1258. * **Use `'help=<str>'` to set argument description.**
  1259. * **Use `'default=<el>'` to set the default value.**
  1260. * **Use `'type=FileType(<mode>)'` for files.**
  1261. Open
  1262. ----
  1263. **Opens a file and returns a corresponding file object.**
  1264. ```python
  1265. <file> = open('<path>', mode='r', encoding=None, newline=None)
  1266. ```
  1267. * **`'encoding=None'` means default encoding is used, which is platform dependent. Best practice is to use `'encoding="utf-8"'` whenever possible.**
  1268. * **`'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.**
  1269. * **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.**
  1270. ### Modes
  1271. * **`'r'` - Read (default).**
  1272. * **`'w'` - Write (truncate).**
  1273. * **`'x'` - Write or fail if the file already exists.**
  1274. * **`'a'` - Append.**
  1275. * **`'w+'` - Read and write (truncate).**
  1276. * **`'r+'` - Read and write from the start.**
  1277. * **`'a+'` - Read and write from the end.**
  1278. * **`'t'` - Text mode (default).**
  1279. * **`'b'` - Binary mode.**
  1280. ### Exceptions
  1281. * **`'FileNotFoundError'` can be risen when reading with `'r'` or `'r+'`.**
  1282. * **`'FileExistsError'` can be risen when writing with `'x'`.**
  1283. * **`'IsADirectoryError'` and `'PermissionError'` can be risen by any.**
  1284. * **`'OSError'` is the parent class of all listed exceptions.**
  1285. ### File
  1286. ```python
  1287. <file>.seek(0) # Moves to the start of the file.
  1288. <file>.seek(offset) # Moves 'offset' chars/bytes from the start.
  1289. <file>.seek(0, 2) # Moves to the end of the file.
  1290. <bin_file>.seek(±offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
  1291. ```
  1292. ```python
  1293. <str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until EOF.
  1294. <str/bytes> = <file>.readline() # Returns a line or empty string on EOF.
  1295. <list> = <file>.readlines() # Returns a list of remaining lines.
  1296. <str/bytes> = next(<file>) # Returns a line using buffer. Do not mix.
  1297. ```
  1298. ```python
  1299. <file>.write(<str/bytes>) # Writes a string or bytes object.
  1300. <file>.writelines(<coll.>) # Writes a coll. of strings or bytes objects.
  1301. <file>.flush() # Flushes write buffer.
  1302. ```
  1303. * **Methods do not add or strip trailing newlines, even writelines().**
  1304. ### Read Text from File
  1305. ```python
  1306. def read_file(filename):
  1307. with open(filename, encoding='utf-8') as file:
  1308. return file.readlines()
  1309. ```
  1310. ### Write Text to File
  1311. ```python
  1312. def write_to_file(filename, text):
  1313. with open(filename, 'w', encoding='utf-8') as file:
  1314. file.write(text)
  1315. ```
  1316. Path
  1317. ----
  1318. ```python
  1319. from os import path, listdir
  1320. from glob import glob
  1321. ```
  1322. ```python
  1323. <bool> = path.exists('<path>')
  1324. <bool> = path.isfile('<path>')
  1325. <bool> = path.isdir('<path>')
  1326. ```
  1327. ```python
  1328. <list> = listdir('<path>') # List of filenames located at path.
  1329. <list> = glob('<pattern>') # Filenames matching the wildcard pattern.
  1330. ```
  1331. ### Pathlib
  1332. ```python
  1333. from pathlib import Path
  1334. ```
  1335. ```python
  1336. cwd = Path()
  1337. <Path> = Path('<path>' [, '<path>', <Path>, ...])
  1338. <Path> = <Path> / '<dir>' / '<file>'
  1339. ```
  1340. ```python
  1341. <bool> = <Path>.exists()
  1342. <bool> = <Path>.is_file()
  1343. <bool> = <Path>.is_dir()
  1344. ```
  1345. ```python
  1346. <iter> = <Path>.iterdir() # Returns dir contents as Path objects.
  1347. <iter> = <Path>.glob('<pattern>') # Returns Paths matching the wildcard pattern.
  1348. ```
  1349. ```python
  1350. <str> = str(<Path>) # Path as a string.
  1351. <str> = <Path>.name # Final component.
  1352. <str> = <Path>.stem # Final component without extension.
  1353. <str> = <Path>.suffix # Final component's extension.
  1354. <tup.> = <Path>.parts # All components as strings.
  1355. ```
  1356. ```python
  1357. <Path> = <Path>.resolve() # Returns absolute path without symlinks.
  1358. <Path> = <Path>.parent # Returns path without final component.
  1359. <file> = open(<Path>) # Opens the file and returns a file object.
  1360. ```
  1361. Command Execution
  1362. -----------------
  1363. ### Files and Directories
  1364. * **Paths can be either strings, Paths, or DirEntry objects.**
  1365. * **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).**
  1366. ```python
  1367. import os, shutil
  1368. ```
  1369. ```python
  1370. os.chdir(<path>) # Changes current working directory.
  1371. os.mkdir(<path>, mode=0o777) # Creates a directory.
  1372. ```
  1373. ```python
  1374. os.rename(from, to) # Renames the file or directory.
  1375. os.replace(from, to) # Same, but overwrites 'to' if it exists.
  1376. ```
  1377. ```python
  1378. os.remove(<path>) # Deletes the file.
  1379. os.rmdir(<path>) # Deletes empty directory.
  1380. shutil.rmtree(<path>) # Deletes the entire directory tree.
  1381. ```
  1382. ```python
  1383. shutil.copy(from, to) # Copies the file.
  1384. shutil.copytree(from, to) # Copies the entire directory tree.
  1385. ```
  1386. ```python
  1387. <str> = os.getcwd() # Returns the current working directory.
  1388. <iter> = os.scandir(path='.') # Returns os.DirEntry objects located at path.
  1389. ```
  1390. #### DirEntry:
  1391. ```python
  1392. <bool> = <DirEntry>.is_file()
  1393. <bool> = <DirEntry>.is_dir()
  1394. ```
  1395. ```python
  1396. <str> = <DirEntry>.path # Path as a string.
  1397. <str> = <DirEntry>.name # Final component.
  1398. ```
  1399. ```python
  1400. <Path> = Path(<DirEntry>) # Path object.
  1401. <file> = open(<DirEntry>) # File object.
  1402. ```
  1403. ### Shell Commands
  1404. ```python
  1405. import os
  1406. <str> = os.popen('<shell_command>').read()
  1407. ```
  1408. #### Using subprocess:
  1409. ```python
  1410. >>> import subprocess, shlex
  1411. >>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE)
  1412. >>> a.stdout
  1413. b'.\n..\nfile1.txt\nfile2.txt\n'
  1414. >>> a.returncode
  1415. 0
  1416. ```
  1417. CSV
  1418. ---
  1419. ```python
  1420. import csv
  1421. ```
  1422. ### Read
  1423. ```python
  1424. <reader> = csv.reader(<file>, dialect='excel', delimiter=',')
  1425. <list> = next(<reader>) # Returns next row as a list of strings.
  1426. <list> = list(<reader>) # Returns list of remaining rows.
  1427. ```
  1428. * **File must be opened with `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!**
  1429. ### Write
  1430. ```python
  1431. <writer> = csv.writer(<file>, dialect='excel', delimiter=',')
  1432. <writer>.writerow(<collection>) # Encodes objects using `str(<el>)`.
  1433. <writer>.writerows(<coll_of_coll>) # Appends multiple rows.
  1434. ```
  1435. * **File must be opened with `'newline=""'` argument, or an extra '\r' will be added on platforms that use '\r\n' linendings!**
  1436. ### Parameters
  1437. * **`'dialect'` - Master parameter that sets the default values.**
  1438. * **`'delimiter'` - A one-character string used to separate fields.**
  1439. * **`'quotechar'` - Character for quoting fields that contain special characters.**
  1440. * **`'doublequote'` - Whether quotechars inside fields get doubled or escaped.**
  1441. * **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped.**
  1442. * **`'lineterminator'` - How does writer terminate lines.**
  1443. * **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.**
  1444. * **`'escapechar'` - Character for escaping 'quotechar' if 'doublequote' is false.**
  1445. ### Dialects
  1446. ```text
  1447. +------------------+-----------+-----------+--------------+
  1448. | | excel | excel_tab | unix_dialect |
  1449. +------------------+-----------+-----------+--------------+
  1450. | delimiter | ',' | '\t' | ',' |
  1451. | quotechar | '"' | '"' | '"' |
  1452. | doublequote | True | True | True |
  1453. | skipinitialspace | False | False | False |
  1454. | lineterminator | '\r\n' | '\r\n' | '\n' |
  1455. | quoting | 0 | 0 | 1 |
  1456. | escapechar | None | None | None |
  1457. +------------------+-----------+-----------+--------------+
  1458. ```
  1459. ### Read Rows from CSV File
  1460. ```python
  1461. def read_csv_file(filename):
  1462. with open(filename, encoding='utf-8', newline='') as file:
  1463. return list(csv.reader(file))
  1464. ```
  1465. ### Write Rows to CSV File
  1466. ```python
  1467. def write_to_csv_file(filename, rows):
  1468. with open(filename, 'w', encoding='utf-8', newline='') as file:
  1469. writer = csv.writer(file)
  1470. writer.writerows(rows)
  1471. ```
  1472. SQLite
  1473. ------
  1474. **Server-less database engine that stores each database into separate file.**
  1475. ```python
  1476. import sqlite3
  1477. db = sqlite3.connect('<path>') # Also ':memory:'.
  1478. ...
  1479. db.close()
  1480. ```
  1481. * **New database will be created if path doesn't exist.**
  1482. ### Read
  1483. ```python
  1484. <cursor> = db.execute('<query>') # Can raise sqlite3.OperationalError.
  1485. <tuple> = <cursor>.fetchone() # Returns next row. Also next(<cursor>).
  1486. <list> = <cursor>.fetchall() # Returns remaining rows.
  1487. ```
  1488. * **Returned values can be of type str, int, float, bytes or None.**
  1489. ### Write
  1490. ```python
  1491. db.execute('<query>')
  1492. db.commit()
  1493. ```
  1494. #### Or:
  1495. ```python
  1496. with db:
  1497. db.execute('<query>')
  1498. ```
  1499. ### Placeholders
  1500. ```python
  1501. db.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
  1502. db.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
  1503. db.executemany('<query>', <coll_of_above>) # Runs execute() many times.
  1504. ```
  1505. * **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.**
  1506. * **Bools will be stored and returned as ints and dates as ISO formatted strings.**
  1507. ### Example
  1508. ```python
  1509. >>> db = sqlite3.connect('test.db')
  1510. >>> db.execute('create table t (a, b, c)')
  1511. >>> db.execute('insert into t values (1, 2, 3)')
  1512. >>> db.execute('select * from t').fetchall()
  1513. [(1, 2, 3)]
  1514. ```
  1515. * **In this example values are not actually saved because `'db.commit()'` was omitted.**
  1516. ### MySQL
  1517. **Has a very similar interface, with differences listed below.**
  1518. ```python
  1519. # $ pip3 install mysql-connector
  1520. from mysql import connector
  1521. db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>)
  1522. <cursor> = db.cursor()
  1523. <cursor>.execute('<query>') # Only cursor has execute method.
  1524. <cursor>.execute('<query>', <list/tuple>) # Replaces '%s's in query with values.
  1525. <cursor>.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.
  1526. ```
  1527. JSON
  1528. ----
  1529. ```python
  1530. import json
  1531. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  1532. <object> = json.loads(<str>)
  1533. ```
  1534. ### Read Object from JSON File
  1535. ```python
  1536. def read_json_file(filename):
  1537. with open(filename, encoding='utf-8') as file:
  1538. return json.load(file)
  1539. ```
  1540. ### Write Object to JSON File
  1541. ```python
  1542. def write_to_json_file(filename, an_object):
  1543. with open(filename, 'w', encoding='utf-8') as file:
  1544. json.dump(an_object, file, ensure_ascii=False, indent=2)
  1545. ```
  1546. Pickle
  1547. ------
  1548. ```python
  1549. import pickle
  1550. <bytes> = pickle.dumps(<object>)
  1551. <object> = pickle.loads(<bytes>)
  1552. ```
  1553. ### Read Object from File
  1554. ```python
  1555. def read_pickle_file(filename):
  1556. with open(filename, 'rb') as file:
  1557. return pickle.load(file)
  1558. ```
  1559. ### Write Object to File
  1560. ```python
  1561. def write_to_pickle_file(filename, an_object):
  1562. with open(filename, 'wb') as file:
  1563. pickle.dump(an_object, file)
  1564. ```
  1565. Bytes
  1566. -----
  1567. **Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.**
  1568. ```python
  1569. <bytes> = b'<str>' # Only accepts ASCII characters and \x00 - \xff.
  1570. <int> = <bytes>[<index>] # Returns int in range from 0 to 255.
  1571. <bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
  1572. <bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes object as separator.
  1573. ```
  1574. ### Encode
  1575. ```python
  1576. <bytes> = bytes(<str>, 'utf-8') # Or: <str>.encode('utf-8')
  1577. <bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
  1578. <bytes> = <int>.to_bytes(n_bytes, byteorder='big|little', signed=False)
  1579. <bytes> = bytes.fromhex('<hex>')
  1580. ```
  1581. ### Decode
  1582. ```python
  1583. <str> = str(<bytes>, 'utf-8') # Or: <bytes>.decode('utf-8')
  1584. <list> = list(<bytes>) # Returns ints in range from 0 to 255.
  1585. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  1586. '<hex>' = <bytes>.hex()
  1587. ```
  1588. ### Read Bytes from File
  1589. ```python
  1590. def read_bytes(filename):
  1591. with open(filename, 'rb') as file:
  1592. return file.read()
  1593. ```
  1594. ### Write Bytes to File
  1595. ```python
  1596. def write_bytes(filename, bytes_obj):
  1597. with open(filename, 'wb') as file:
  1598. file.write(bytes_obj)
  1599. ```
  1600. Struct
  1601. ------
  1602. * **Module that performs conversions between a sequence of numbers and a bytes object.**
  1603. * **Machine’s native type sizes and byte order are used by default.**
  1604. ```python
  1605. from struct import pack, unpack, iter_unpack
  1606. <bytes> = pack('<format>', <num_1> [, <num_2>, ...])
  1607. <tuple> = unpack('<format>', <bytes>)
  1608. <tuples> = iter_unpack('<format>', <bytes>)
  1609. ```
  1610. ### Example
  1611. ```python
  1612. >>> pack('>hhl', 1, 2, 3)
  1613. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  1614. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  1615. (1, 2, 3)
  1616. ```
  1617. ### Format
  1618. #### For standard sizes start format string with:
  1619. * **`'='` - native byte order**
  1620. * **`'<'` - little-endian**
  1621. * **`'>'` - big-endian**
  1622. #### Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:
  1623. * **`'x'` - pad byte**
  1624. * **`'b'` - char (1)**
  1625. * **`'h'` - short (2)**
  1626. * **`'i'` - int (4)**
  1627. * **`'l'` - long (4)**
  1628. * **`'q'` - long long (8)**
  1629. #### Floating point types:
  1630. * **`'f'` - float (4)**
  1631. * **`'d'` - double (8)**
  1632. Array
  1633. -----
  1634. **List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.**
  1635. ```python
  1636. from array import array
  1637. <array> = array('<typecode>', <collection>) # Array from coll. of numbers.
  1638. <array> = array('<typecode>', <bytes>) # Array from bytes object.
  1639. <bytes> = <array>.tobytes()
  1640. ```
  1641. Memory View
  1642. -----------
  1643. **Used for accessing the internal data of an object that supports the buffer protocol.**
  1644. ```python
  1645. <mview> = memoryview(<bytes> / <bytearray> / <array>)
  1646. <mview>.release() # Releases the buffer.
  1647. ```
  1648. ```python
  1649. <num> = <mview>[<index>] # Returns int in range from 0 to 255.
  1650. <mview> = <mview>[<slice>] # Returns bytes even if it has only one element.
  1651. <file>.write(<mview>)
  1652. ```
  1653. ```python
  1654. <bytes> = <bytes>.join(<coll_of_mviews>) # Joins elements using bytes object as separator.
  1655. <bytes> = bytes(<mview>) # Or: <mview>.tobytes()
  1656. '<hex>' = <mview>.hex()
  1657. <list> = list(<mview>) # Returns numbers.
  1658. <str> = str(<mview>, 'utf-8') # Or: <bytes>.decode('utf-8')
  1659. <int> = int.from_bytes(<mview>, byteorder='big|little', signed=False)
  1660. '<hex>' = <bytes>.hex()
  1661. ```
  1662. Deque
  1663. -----
  1664. **A thread-safe list with efficient appends and pops from either side. Pronounced "deck".**
  1665. ```python
  1666. from collections import deque
  1667. <deque> = deque(<collection>, maxlen=None)
  1668. ```
  1669. ```python
  1670. <deque>.appendleft(<el>) # Opposite element is dropped if full.
  1671. <el> = <deque>.popleft() # Raises IndexError if empty.
  1672. <deque>.extendleft(<collection>) # Collection gets reversed.
  1673. <deque>.rotate(n=1) # Rotates elements to the right.
  1674. ```
  1675. Threading
  1676. ---------
  1677. * **CPython interpreter can only run a single thread at a time.**
  1678. * **That is why using multiple threads won't result in a faster execution, unless there is an I/O operation in the thread.**
  1679. ```python
  1680. from threading import Thread, RLock
  1681. ```
  1682. ### Thread
  1683. ```python
  1684. thread = Thread(target=<function>, args=(<first_arg>, ))
  1685. thread.start()
  1686. ...
  1687. <bool> = thread.is_alive() # Checks if thread has finished executing.
  1688. thread.join() # Waits for thread to finish.
  1689. ```
  1690. ### Lock
  1691. ```python
  1692. lock = RLock()
  1693. lock.acquire() # Waits for lock to be available.
  1694. ...
  1695. lock.release()
  1696. ```
  1697. #### Or:
  1698. ```python
  1699. lock = RLock()
  1700. with lock:
  1701. ...
  1702. ```
  1703. ### Thread Pool
  1704. ```python
  1705. from concurrent.futures import ThreadPoolExecutor
  1706. with ThreadPoolExecutor(max_workers=None) as executor:
  1707. <iter> = executor.map(lambda x: x + 1, range(3)) # (1, 2, 3)
  1708. <iter> = executor.map(lambda x, y: x + y, 'abc', '123') # ('a1', 'b2', 'c3')
  1709. <Future> = executor.submit(<function> [, <arg_1>, ...])
  1710. ```
  1711. ```python
  1712. <bool> = <Future>.done() # Checks if thread has finished executing.
  1713. <obj> = <Future>.result() # Waits for thread to finish and returns result.
  1714. ```
  1715. ### Queue
  1716. **A thread-safe FIFO queue. For LIFO queue use LifoQueue.**
  1717. ```python
  1718. from queue import Queue
  1719. <Queue> = Queue(maxsize=0)
  1720. ```
  1721. ```python
  1722. <Queue>.put(<el>) # Blocks until queue stops being full.
  1723. <Queue>.put_nowait(<el>) # Raises queue.Full exception if full.
  1724. <el> = <Queue>.get() # Blocks until queue stops being empty.
  1725. <el> = <Queue>.get_nowait() # Raises _queue.Empty exception if empty.
  1726. ```
  1727. Operator
  1728. --------
  1729. ```python
  1730. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
  1731. from operator import eq, ne, lt, le, gt, ge
  1732. from operator import and_, or_, not_
  1733. from operator import itemgetter, attrgetter, methodcaller
  1734. ```
  1735. ```python
  1736. import operator as op
  1737. sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
  1738. sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
  1739. product_of_elems = functools.reduce(op.mul, <collection>)
  1740. LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
  1741. last_el = op.methodcaller('pop')(<list>)
  1742. ```
  1743. Introspection
  1744. -------------
  1745. **Inspecting code at runtime.**
  1746. ### Variables
  1747. ```python
  1748. <list> = dir() # Names of variables in current scope.
  1749. <dict> = locals() # Dict of local variables. Also vars().
  1750. <dict> = globals() # Dict of global variables.
  1751. ```
  1752. ### Attributes
  1753. ```python
  1754. <dict> = vars(<object>)
  1755. <bool> = hasattr(<object>, '<attr_name>')
  1756. value = getattr(<object>, '<attr_name>')
  1757. setattr(<object>, '<attr_name>', value)
  1758. ```
  1759. ### Parameters
  1760. ```python
  1761. from inspect import signature
  1762. <sig> = signature(<function>)
  1763. no_of_params = len(<sig>.parameters)
  1764. param_names = list(<sig>.parameters.keys())
  1765. ```
  1766. Metaprograming
  1767. --------------
  1768. **Code that generates code.**
  1769. ### Type
  1770. **Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.**
  1771. ```python
  1772. <class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
  1773. ```
  1774. ```python
  1775. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  1776. >>> z = Z()
  1777. ```
  1778. ### Meta Class
  1779. **Class that creates classes.**
  1780. ```python
  1781. def my_meta_class(name, parents, attrs):
  1782. attrs['a'] = 'abcde'
  1783. return type(name, parents, attrs)
  1784. ```
  1785. #### Or:
  1786. ```python
  1787. class MyMetaClass(type):
  1788. def __new__(cls, name, parents, attrs):
  1789. attrs['a'] = 'abcde'
  1790. return type.__new__(cls, name, parents, attrs)
  1791. ```
  1792. * **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.**
  1793. * **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (MyMetaClass in our case).**
  1794. * **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.**
  1795. ### Metaclass Attribute
  1796. **Right before a class is created it checks if it has metaclass attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().**
  1797. ```python
  1798. class MyClass(metaclass=MyMetaClass):
  1799. b = 12345
  1800. ```
  1801. ```python
  1802. >>> MyClass.a, MyClass.b
  1803. ('abcde', 12345)
  1804. ```
  1805. ### Type Diagram
  1806. ```python
  1807. type(MyClass) == MyMetaClass # MyClass is an instance of MyMetaClass.
  1808. type(MyMetaClass) == type # MyMetaClass is an instance of type.
  1809. ```
  1810. ```text
  1811. +---------+-------------+
  1812. | Classes | Metaclasses |
  1813. +---------+-------------|
  1814. | MyClass > MyMetaClass |
  1815. | | v |
  1816. | object ---> type <+ |
  1817. | | ^ +---+ |
  1818. | str -------+ |
  1819. +---------+-------------+
  1820. ```
  1821. ### Inheritance Diagram
  1822. ```python
  1823. MyClass.__base__ == object # MyClass is a subclass of object.
  1824. MyMetaClass.__base__ == type # MyMetaClass is a subclass of type.
  1825. ```
  1826. ```text
  1827. +---------+-------------+
  1828. | Classes | Metaclasses |
  1829. +---------+-------------|
  1830. | MyClass | MyMetaClass |
  1831. | v | v |
  1832. | object <--- type |
  1833. | ^ | |
  1834. | str | |
  1835. +---------+-------------+
  1836. ```
  1837. Eval
  1838. ----
  1839. ```python
  1840. >>> from ast import literal_eval
  1841. >>> literal_eval('1 + 2')
  1842. 3
  1843. >>> literal_eval('[1, 2, 3]')
  1844. [1, 2, 3]
  1845. >>> literal_eval('abs(1)')
  1846. ValueError: malformed node or string
  1847. ```
  1848. Coroutine
  1849. ---------
  1850. * **Any function that contains a `'(yield)'` expression returns a coroutine.**
  1851. * **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>)'`.**
  1852. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1853. ### Helper Decorator
  1854. * **All coroutines must first be "primed" by calling `'next(<coroutine>)'`.**
  1855. * **Remembering to call next() is easy to forget.**
  1856. * **Solved by wrapping functions that return a coroutine with a decorator:**
  1857. ```python
  1858. def coroutine(func):
  1859. def out(*args, **kwargs):
  1860. cr = func(*args, **kwargs)
  1861. next(cr)
  1862. return cr
  1863. return out
  1864. ```
  1865. ### Pipeline Example
  1866. ```python
  1867. def reader(target):
  1868. for i in range(10):
  1869. target.send(i)
  1870. target.close()
  1871. @coroutine
  1872. def adder(target):
  1873. while True:
  1874. value = (yield)
  1875. target.send(value + 100)
  1876. @coroutine
  1877. def printer():
  1878. while True:
  1879. value = (yield)
  1880. print(value)
  1881. reader(adder(printer())) # 100, 101, ..., 109
  1882. ```
  1883. <br><br>
  1884. Libraries
  1885. =========
  1886. Progress Bar
  1887. ------------
  1888. ```python
  1889. # $ pip3 install tqdm
  1890. from tqdm import tqdm
  1891. from time import sleep
  1892. for el in tqdm([1, 2, 3]):
  1893. sleep(0.2)
  1894. ```
  1895. Plot
  1896. ----
  1897. ```python
  1898. # $ pip3 install matplotlib
  1899. from matplotlib import pyplot
  1900. ```
  1901. ```python
  1902. pyplot.plot(<y_data>)
  1903. pyplot.plot(<x_data>, <y_data>)
  1904. pyplot.plot(..., label=<str>) # Use `pyplot.legend()` to add legend.
  1905. pyplot.savefig(<filename>) # Saves figure.
  1906. pyplot.show() # Displays figure.
  1907. pyplot.clf() # Clears figure.
  1908. ```
  1909. Table
  1910. -----
  1911. #### Prints a CSV file as an ASCII table:
  1912. ```python
  1913. # $ pip3 install tabulate
  1914. from tabulate import tabulate
  1915. import csv
  1916. with open(<filename>, encoding='utf-8', newline='') as file:
  1917. rows = csv.reader(file)
  1918. header = [a.title() for a in next(rows)]
  1919. table = tabulate(rows, header)
  1920. print(table)
  1921. ```
  1922. Curses
  1923. ------
  1924. ```python
  1925. from curses import wrapper, curs_set, ascii
  1926. from curses import KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT
  1927. def main():
  1928. wrapper(draw)
  1929. def draw(screen):
  1930. curs_set(0) # Makes cursor invisible.
  1931. screen.nodelay(True) # Makes getch() non-blocking.
  1932. screen.clear()
  1933. screen.addstr(0, 0, 'Press ESC to quit.')
  1934. while screen.getch() != ascii.ESC:
  1935. pass
  1936. def get_border(screen):
  1937. from collections import namedtuple
  1938. P = namedtuple('P', 'x y')
  1939. height, width = screen.getmaxyx()
  1940. return P(width-1, height-1)
  1941. if __name__ == '__main__':
  1942. main()
  1943. ```
  1944. Logging
  1945. -------
  1946. ```python
  1947. # $ pip3 install loguru
  1948. from loguru import logger
  1949. ```
  1950. ```python
  1951. logger.add('debug_{time}.log', colorize=True) # Connects a log file.
  1952. logger.add('error_{time}.log', level='ERROR') # Another file for errors or higher.
  1953. logger.<level>('A logging message.')
  1954. ```
  1955. * **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.**
  1956. ### Exceptions
  1957. **Exception description, stack trace and values of variables are appended automatically.**
  1958. ```python
  1959. try:
  1960. ...
  1961. except <exception>:
  1962. logger.exception('An error happened.')
  1963. ```
  1964. ### Rotation
  1965. **Argument that sets a condition when a new log file is created.**
  1966. ```python
  1967. rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
  1968. ```
  1969. * **`'<int>'` - Max file size in bytes.**
  1970. * **`'<timedelta>'` - Max age of a file.**
  1971. * **`'<time>'` - Time of day.**
  1972. * **`'<str>'` - Any of above as a string: `'100 MB'`, `'1 month'`, `'monday at 12:00'`, ...**
  1973. ### Retention
  1974. **Sets a condition which old log files are deleted.**
  1975. ```python
  1976. retention=<int>|<datetime.timedelta>|<str>
  1977. ```
  1978. * **`'<int>'` - Max number of files.**
  1979. * **`'<timedelta>'` - Max age of a file.**
  1980. * **`'<str>'` - Max age as a string: `'1 week, 3 days'`, `'2 months'`, ...**
  1981. Scraping
  1982. --------
  1983. #### Scrapes Python's URL, version number and logo from Wikipedia page:
  1984. ```python
  1985. # $ pip3 install requests beautifulsoup4
  1986. import requests
  1987. from bs4 import BeautifulSoup
  1988. url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1989. html = requests.get(url).text
  1990. doc = BeautifulSoup(html, 'html.parser')
  1991. table = doc.find('table', class_='infobox vevent')
  1992. rows = table.find_all('tr')
  1993. link = rows[11].find('a')['href']
  1994. ver = rows[6].find('div').text.split()[0]
  1995. url_i = rows[0].find('img')['src']
  1996. image = requests.get(f'https:{url_i}').content
  1997. with open('test.png', 'wb') as file:
  1998. file.write(image)
  1999. print(link, ver)
  2000. ```
  2001. Web
  2002. ---
  2003. ```python
  2004. # $ pip3 install bottle
  2005. from bottle import run, route, post, template, request, response
  2006. import json
  2007. ```
  2008. ### Run
  2009. ```python
  2010. run(host='localhost', port=8080)
  2011. run(host='0.0.0.0', port=80, server='cherrypy')
  2012. ```
  2013. ### Static Request
  2014. ```python
  2015. @route('/img/<image>')
  2016. def send_image(image):
  2017. return static_file(image, 'images/', mimetype='image/png')
  2018. ```
  2019. ### Dynamic Request
  2020. ```python
  2021. @route('/<sport>')
  2022. def send_page(sport):
  2023. return template('<h1>{{title}}</h1>', title=sport)
  2024. ```
  2025. ### REST Request
  2026. ```python
  2027. @post('/odds/<sport>')
  2028. def odds_handler(sport):
  2029. team = request.forms.get('team')
  2030. home_odds, away_odds = 2.44, 3.29
  2031. response.headers['Content-Type'] = 'application/json'
  2032. response.headers['Cache-Control'] = 'no-cache'
  2033. return json.dumps([team, home_odds, away_odds])
  2034. ```
  2035. #### Test:
  2036. ```python
  2037. # $ pip3 install requests
  2038. >>> import requests
  2039. >>> url = 'http://localhost:8080/odds/football'
  2040. >>> data = {'team': 'arsenal f.c.'}
  2041. >>> response = requests.post(url, data=data)
  2042. >>> response.json()
  2043. ['arsenal f.c.', 2.44, 3.29]
  2044. ```
  2045. Profiling
  2046. ---------
  2047. ### Stopwatch
  2048. ```python
  2049. from time import time
  2050. start_time = time() # Seconds since the Epoch.
  2051. ...
  2052. duration = time() - start_time
  2053. ```
  2054. #### High performance:
  2055. ```python
  2056. from time import perf_counter
  2057. start_time = perf_counter() # Seconds since restart.
  2058. ...
  2059. duration = perf_counter() - start_time
  2060. ```
  2061. ### Timing a Snippet
  2062. ```python
  2063. >>> from timeit import timeit
  2064. >>> timeit('"-".join(str(a) for a in range(100))',
  2065. ... number=10000, globals=globals(), setup='pass')
  2066. 0.34986
  2067. ```
  2068. ### Profiling by Line
  2069. ```python
  2070. # $ pip3 install line_profiler memory_profiler
  2071. @profile
  2072. def main():
  2073. a = [*range(10000)]
  2074. b = {*range(10000)}
  2075. main()
  2076. ```
  2077. ```text
  2078. $ kernprof -lv test.py
  2079. Line # Hits Time Per Hit % Time Line Contents
  2080. =======================================================
  2081. 1 @profile
  2082. 2 def main():
  2083. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  2084. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  2085. ```
  2086. ```text
  2087. $ python3 -m memory_profiler test.py
  2088. Line # Mem usage Increment Line Contents
  2089. =======================================================
  2090. 1 35.387 MiB 35.387 MiB @profile
  2091. 2 def main():
  2092. 3 35.734 MiB 0.348 MiB a = [*range(10000)]
  2093. 4 36.160 MiB 0.426 MiB b = {*range(10000)}
  2094. ```
  2095. ### Call Graph
  2096. #### Generates a PNG image of a call graph with highlighted bottlenecks:
  2097. ```python
  2098. # $ pip3 install pycallgraph
  2099. from pycallgraph import output, PyCallGraph
  2100. from datetime import datetime
  2101. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  2102. filename = f'profile-{time_str}.png'
  2103. drawer = output.GraphvizOutput(output_file=filename)
  2104. with PyCallGraph(drawer):
  2105. <code_to_be_profiled>
  2106. ```
  2107. NumPy
  2108. -----
  2109. **Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.**
  2110. ```python
  2111. # $ pip3 install numpy
  2112. import numpy as np
  2113. ```
  2114. ```python
  2115. <array> = np.array(<list>)
  2116. <array> = np.arange(from_inclusive, to_exclusive, ±step_size)
  2117. <array> = np.ones(<shape>)
  2118. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  2119. ```
  2120. ```python
  2121. <array>.shape = <shape>
  2122. <view> = <array>.reshape(<shape>)
  2123. <view> = np.broadcast_to(<array>, <shape>)
  2124. ```
  2125. ```python
  2126. <array> = <array>.sum(axis)
  2127. indexes = <array>.argmin(axis)
  2128. ```
  2129. * **Shape is a tuple of dimension sizes.**
  2130. * **Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.**
  2131. ### Indexing
  2132. ```bash
  2133. <el> = <2d_array>[0, 0] # First element.
  2134. <1d_view> = <2d_array>[0] # First row.
  2135. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0].
  2136. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1.
  2137. ```
  2138. ```bash
  2139. <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
  2140. <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
  2141. ```
  2142. ```bash
  2143. <2d_bools> = <2d_array> > 0
  2144. <1d_array> = <2d_array>[<2d_bools>]
  2145. ```
  2146. * **If row and column indexes differ in shape, they are combined with broadcasting.**
  2147. ### Broadcasting
  2148. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  2149. ```python
  2150. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  2151. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  2152. ```
  2153. #### 1. If array shapes differ in length, left-pad the shorter shape with ones:
  2154. ```python
  2155. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  2156. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  2157. ```
  2158. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  2159. ```python
  2160. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  2161. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  2162. ```
  2163. #### 3. If neither non-matching dimension has size 1, rise an error.
  2164. ### Example
  2165. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  2166. ```python
  2167. >>> points = np.array([0.1, 0.6, 0.8])
  2168. [ 0.1, 0.6, 0.8]
  2169. >>> wrapped_points = points.reshape(3, 1)
  2170. [[ 0.1],
  2171. [ 0.6],
  2172. [ 0.8]]
  2173. >>> distances = wrapped_points - points
  2174. [[ 0. , -0.5, -0.7],
  2175. [ 0.5, 0. , -0.2],
  2176. [ 0.7, 0.2, 0. ]]
  2177. >>> distances = np.abs(distances)
  2178. [[ 0. , 0.5, 0.7],
  2179. [ 0.5, 0. , 0.2],
  2180. [ 0.7, 0.2, 0. ]]
  2181. >>> i = np.arange(3)
  2182. [0, 1, 2]
  2183. >>> distances[i, i] = np.inf
  2184. [[ inf, 0.5, 0.7],
  2185. [ 0.5, inf, 0.2],
  2186. [ 0.7, 0.2, inf]]
  2187. >>> distances.argmin(1)
  2188. [1, 2, 1]
  2189. ```
  2190. Image
  2191. -----
  2192. ```python
  2193. # $ pip3 install pillow
  2194. from PIL import Image
  2195. ```
  2196. ```python
  2197. <Image> = Image.new('<mode>', (width, height))
  2198. <Image> = Image.open('<path>')
  2199. <Image> = <Image>.convert('<mode>')
  2200. <Image>.save('<path>')
  2201. <Image>.show()
  2202. ```
  2203. ```python
  2204. <tuple/int> = <Image>.getpixel((x, y)) # Returns a pixel.
  2205. <Image>.putpixel((x, y), <tuple/int>) # Writes a pixel to image.
  2206. <ImagingCore> = <Image>.getdata() # Returns a sequence of pixels.
  2207. <Image>.putdata(<list/tuple>) # Writes a sequence of pixels.
  2208. <Image>.paste(<Image>, (x, y)) # Writes an image to image.
  2209. ```
  2210. ### Modes
  2211. * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.**
  2212. * **`'L'` - 8-bit pixels, greyscale.**
  2213. * **`'RGB'` - 3x8-bit pixels, true color.**
  2214. * **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.**
  2215. * **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.**
  2216. ### Examples
  2217. #### Creates a PNG image of a rainbow gradient:
  2218. ```python
  2219. WIDTH, HEIGHT = 100, 100
  2220. size = WIDTH * HEIGHT
  2221. hue = [255 * i/size for i in range(size)]
  2222. img = Image.new('HSV', (WIDTH, HEIGHT))
  2223. img.putdata([(int(h), 255, 255) for h in hue])
  2224. img.convert('RGB').save('test.png')
  2225. ```
  2226. #### Adds noise to a PNG image:
  2227. ```python
  2228. from random import randint
  2229. add_noise = lambda value: max(0, min(255, value + randint(-20, 20)))
  2230. img = Image.open('test.png').convert('HSV')
  2231. img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
  2232. img.convert('RGB').save('test.png')
  2233. ```
  2234. ### ImageDraw
  2235. ```python
  2236. from PIL import ImageDraw
  2237. ```
  2238. ```python
  2239. <ImageDraw> = ImageDraw.Draw(<Image>)
  2240. <ImageDraw>.point((x, y), fill=None)
  2241. <ImageDraw>.line((x1, y1, x2, y2 [, ...]), fill=None, width=0, joint=None)
  2242. <ImageDraw>.arc((x1, y1, x2, y2), from_deg, to_deg, fill=None, width=0)
  2243. <ImageDraw>.rectangle((x1, y1, x2, y2), fill=None, outline=None, width=0)
  2244. <ImageDraw>.polygon((x1, y1, x2, y2 [, ...]), fill=None, outline=None)
  2245. <ImageDraw>.ellipse((x1, y1, x2, y2), fill=None, outline=None, width=0)
  2246. ```
  2247. * **Use `'fill=<color>'` to set the primary color.**
  2248. * **Use `'outline=<color>'` to set the secondary color.**
  2249. * **Colors can be specified as tuple, int, `'#rrggbb'` string or a color name.**
  2250. Animation
  2251. ---------
  2252. #### Creates a GIF of a bouncing ball:
  2253. ```python
  2254. # $ pip3 install pillow imageio
  2255. from PIL import Image, ImageDraw
  2256. import imageio
  2257. WIDTH, R = 126, 10
  2258. frames = []
  2259. for velocity in range(15):
  2260. y = sum(range(velocity+1))
  2261. frame = Image.new('L', (WIDTH, WIDTH))
  2262. draw = ImageDraw.Draw(frame)
  2263. draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+2*R), fill='white')
  2264. frames.append(frame)
  2265. frames += reversed(frames[1:-1])
  2266. imageio.mimsave('test.gif', frames, duration=0.03)
  2267. ```
  2268. Audio
  2269. -----
  2270. ```python
  2271. import wave
  2272. ```
  2273. ```python
  2274. <Wave_read> = wave.open('<path>', 'rb')
  2275. framerate = <Wave_read>.getframerate() # Number of frames per second.
  2276. nchannels = <Wave_read>.getnchannels() # Number of samples per frame.
  2277. sampwidth = <Wave_read>.getsampwidth() # Sample size in bytes.
  2278. nframes = <Wave_read>.getnframes() # Number of frames.
  2279. <bytes> = <Wave_read>.readframes(nframes) # Returns next 'nframes' frames.
  2280. ```
  2281. ```python
  2282. <Wave_write> = wave.open('<path>', 'wb')
  2283. <Wave_write>.setframerate(<int>) # 44100 for CD, 48000 for video.
  2284. <Wave_write>.setnchannels(<int>) # 1 for mono, 2 for stereo.
  2285. <Wave_write>.setsampwidth(<int>) # 2 for CD quality sound.
  2286. <Wave_write>.writeframes(<bytes>) # Appends frames to file.
  2287. ```
  2288. * **Bytes object contains a sequence of frames, each consisting of one or more samples.**
  2289. * **In stereo signal first sample of a frame belongs to the left channel.**
  2290. * **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.**
  2291. * **If sample width is one, then the integer should be encoded unsigned.**
  2292. * **For all other sizes the integer should be encoded signed with little-endian byte order.**
  2293. ### Sample Values
  2294. ```text
  2295. +-----------+-------------+------+-------------+
  2296. | sampwidth | min | zero | max |
  2297. +-----------+-------------+------+-------------+
  2298. | 1 | 0 | 128 | 255 |
  2299. | 2 | -32768 | 0 | 32767 |
  2300. | 3 | -8388608 | 0 | 8388607 |
  2301. | 4 | -2147483648 | 0 | 2147483647 |
  2302. +-----------+-------------+------+-------------+
  2303. ```
  2304. ### Read Float Frames from WAV File
  2305. ```python
  2306. def read_wav_file(filename):
  2307. def get_int(a_bytes):
  2308. an_int = int.from_bytes(a_bytes, 'little', signed=width!=1)
  2309. return an_int - 128 * (width == 1)
  2310. with wave.open(filename, 'rb') as file:
  2311. frames = file.readframes(file.getnframes())
  2312. width = file.getsampwidth()
  2313. chunks = (frames[i: i + width] for i in range(0, len(frames), width))
  2314. return [get_int(a) / pow(2, width * 8 - 1) for a in chunks]
  2315. ```
  2316. ### Write Float Frames to WAV File
  2317. ```python
  2318. def write_to_wav_file(filename, frames_float, nchannels=1, sampwidth=2, framerate=44100):
  2319. def get_bytes(a_float):
  2320. a_float = max(-1, min(1 - 2e-16, a_float))
  2321. a_float += sampwidth == 1
  2322. a_float *= pow(2, sampwidth * 8 - 1)
  2323. return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1)
  2324. with wave.open(filename, 'wb') as file:
  2325. file.setnchannels(nchannels)
  2326. file.setsampwidth(sampwidth)
  2327. file.setframerate(framerate)
  2328. file.writeframes(b''.join(get_bytes(a) for a in frames_float))
  2329. ```
  2330. ### Examples
  2331. #### Saves a sine wave to a mono WAV file:
  2332. ```python
  2333. from math import pi, sin
  2334. frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
  2335. write_to_wav_file('test.wav', frames_f)
  2336. ```
  2337. #### Adds noise to a mono WAV file:
  2338. ```python
  2339. from random import random
  2340. add_noise = lambda value: value + (random()-0.5) * 0.03
  2341. frames_f = (add_noise(a) for a in read_wav_file('test.wav'))
  2342. write_to_wav_file('test.wav', frames_f)
  2343. ```
  2344. Synthesizer
  2345. -----------
  2346. #### Plays Popcorn by Gershon Kingsley:
  2347. ```python
  2348. # $ pip3 install simpleaudio
  2349. import simpleaudio, math, struct
  2350. from itertools import chain, repeat
  2351. F = 44100
  2352. P1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,'
  2353. P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'
  2354. get_pause = lambda seconds: repeat(0, int(seconds * F))
  2355. sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
  2356. get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
  2357. get_hz = lambda key: 8.176 * 2 ** (int(key) / 12)
  2358. parse_note = lambda note: (get_hz(note[:2]), 0.25 if '♪' in note else 0.125)
  2359. get_frames = lambda note: get_wave(*parse_note(note)) if note else get_pause(0.125)
  2360. frames_f = chain.from_iterable(get_frames(n) for n in f'{P1}{P1}{P2}'.split(','))
  2361. frames_b = b''.join(struct.pack('<h', int(f * 30000)) for f in frames_f)
  2362. simpleaudio.play_buffer(frames_b, 1, 2, F)
  2363. ```
  2364. Basic Script Template
  2365. ---------------------
  2366. ```python
  2367. #!/usr/bin/env python3
  2368. #
  2369. # Usage: .py
  2370. #
  2371. from collections import namedtuple
  2372. from dataclasses import make_dataclass
  2373. from enum import Enum
  2374. import re
  2375. import sys
  2376. def main():
  2377. pass
  2378. ###
  2379. ## UTIL
  2380. #
  2381. def read_file(filename):
  2382. with open(filename, encoding='utf-8') as file:
  2383. return file.readlines()
  2384. if __name__ == '__main__':
  2385. main()
  2386. ```