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.

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