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.

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