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.

2879 lines
88 KiB

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