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.

2889 lines
89 KiB

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