diff --git a/README.md b/README.md index 19637c4ad..45697179f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/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). +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). ![Monty Python](web/image_888.jpeg) @@ -10,74 +10,88 @@ Contents -------- **   ** **1. Collections:** ** ** **[`List`](#list)**__,__ **[`Dictionary`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__ **   ** **2. Types:** **          ** **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regular_Exp`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers-1)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__ -**   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__ +**   ** **3. Syntax:** **         ** **[`Function`](#function)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Except`](#exceptions)**__.__ **   ** **4. System:** **        ** **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__ **   ** **5. Data:** **             ** **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__ -**   ** **6. Advanced:** **   ** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprogramming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__ -**   ** **7. Libraries:** **      ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`Logging`](#logging)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profile`](#profiling)**__,__ -**                                 ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Audio`](#audio)**__,__ **[`Games`](#pygame)**__,__ **[`Data`](#pandas)**__.__ +**   ** **6. Advanced:** **   ** **[`Operator`](#operator)**__,__ **[`Match_Stmt`](#match-statement)**__,__ **[`Logging`](#logging)**__,__ **[`Introspection`](#introspection)**__,__ **[`Threading`](#threading)**__,__ **[`Coroutines`](#coroutines)**__.__ +**   ** **7. Libraries:** **      ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Console_App`](#console-app)**__,__ **[`GUI`](#gui-app)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web-app)**__,__ **[`Profile`](#profiling)**__.__ +**   ** **8. Multimedia:** **  ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Animation`](#animation)**__,__ **[`Audio`](#audio)**__,__ **[`Synthesizer`](#synthesizer)**__,__ **[`Pygame`](#pygame)**__,__ **[`Pandas`](#pandas)**__,__ **[`Plotly`](#plotly)**__.__ Main ---- ```python -if __name__ == '__main__': # Runs main() if file wasn't imported. - main() +if __name__ == '__main__': # Skips next line if file was imported. + main() # Runs `def main(): ...` function. ``` List ---- ```python - = [from_inclusive : to_exclusive : ±step_size] + = [, , ...] # Creates a list object. Also list(). +``` + +```python + = [index] # First index is 0. Last -1. Allows assignments. + = [] # Also [from_inclusive : to_exclusive : ±step]. ``` ```python -.append() # Or: += [] -.extend() # Or: += +.append() # Appends element to the end. Also += []. +.extend() # Appends elements to the end. Also += . ``` ```python -.sort() -.reverse() - = sorted() - = reversed() +.sort() # Sorts elements in ascending order. +.reverse() # Reverses the list in-place. + = sorted() # Returns new list with sorted elements. + = reversed() # Returns reversed iterator of elements. +``` + +```python + = max() # Returns largest element. Also min(, ...). + = sum() # Returns sum of elements. Also math.prod(). ``` ```python -sum_of_elements = sum() elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flatter_list = list(itertools.chain.from_iterable()) -product_of_elems = functools.reduce(lambda out, el: out * el, ) -list_of_chars = list() ``` -* **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.** +* **For details about sort(), sorted(), min() and max() see [Sortable](#sortable).** +* **Module [operator](#operator) has function itemgetter() that can replace listed [lambdas](#lambda).** +* **This text uses the term collection instead of iterable. For rationale see [Collection](#collection).** ```python -.insert(, ) # Inserts item at index and moves the rest to the right. - = .pop([]) # Returns and removes item at index or from the end. - = .count() # Returns number of occurrences. Also works on strings. - = .index() # Returns index of the first occurrence or raises ValueError. -.remove() # Removes first occurrence of the item or raises ValueError. -.clear() # Removes all items. Also works on dictionary and set. + = len() # Returns number of items. Also works on dict, set and string. + = .count() # Returns number of occurrences. Also `if in : ...`. + = .index() # Returns index of the first occurrence or raises ValueError. + = .pop() # Removes and returns item from the end or at index if passed. +.insert(, ) # Inserts item at index and moves the rest to the right. +.remove() # Removes first occurrence of the item or raises ValueError. +.clear() # Removes all items. Also works on dictionary and set. ``` Dictionary ---------- ```python - = .keys() # Coll. of keys that reflects changes. - = .values() # Coll. of values that reflects changes. + = {key_1: val_1, key_2: val_2, ...} # Use `[key]` to get or set the value. +``` + +```python + = .keys() # Collection of keys that reflects changes. + = .values() # Collection of values that reflects changes. = .items() # Coll. of key-value tuples that reflects chgs. ``` ```python value = .get(key, default=None) # Returns default if key is missing. value = .setdefault(key, default=None) # Returns and writes default if key is missing. - = collections.defaultdict() # Creates a dict with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dict with default value 1. + = collections.defaultdict() # Returns a dict with default value `()`. + = collections.defaultdict(lambda: 1) # Returns a dict with default value 1. ``` ```python @@ -88,27 +102,25 @@ value = .setdefault(key, default=None) # Returns and writes default if ```python .update() # Adds items. Replaces ones with matching keys. -value = .pop(key) # Removes item or raises KeyError. +value = .pop(key) # Removes item or raises KeyError if missing. {k for k, v in .items() if v == value} # Returns set of keys that point to the value. -{k: v for k, v in .items() if k in keys} # Returns a dictionary, filtered by keys. +{k: v for k, v in .items() if k in keys} # Filters the dictionary by keys. ``` ### Counter ```python >>> from collections import Counter ->>> colors = ['blue', 'blue', 'blue', 'red', 'red'] ->>> counter = Counter(colors) +>>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red']) >>> counter['yellow'] += 1 -Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> counter.most_common()[0] -('blue', 3) +>>> print(counter.most_common()) +[('blue', 3), ('red', 2), ('yellow', 1)] ``` Set --- ```python - = set() + = {, , ...} # Use `set()` for empty set. ``` ```python @@ -143,80 +155,77 @@ Tuple ----- **Tuple is an immutable and hashable list.** ```python - = () - = (,) # Or: , - = (, [, ...]) # Or: , [, ...] + = () # Empty tuple. + = (,) # Or: , + = (, [, ...]) # Or: , [, ...] ``` ### Named Tuple **Tuple's subclass with named elements.** - ```python >>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2) +>>> print(p) Point(x=1, y=2) ->>> p[0] -1 ->>> p.x -1 ->>> getattr(p, 'y') -2 ->>> p._fields # Or: Point._fields -('x', 'y') +>>> p[0], p.x +(1, 1) ``` Range ----- +**Immutable and hashable sequence of integers.** ```python - = range(to_exclusive) - = range(from_inclusive, to_exclusive) - = range(from_inclusive, to_exclusive, ±step_size) + = range(stop) # I.e. range(to_exclusive). + = range(start, stop) # I.e. range(from_inclusive, to_exclusive). + = range(start, stop, ±step) # I.e. range(from_inclusive, to_exclusive, ±step). ``` ```python -from_inclusive = .start -to_exclusive = .stop +>>> [i for i in range(3)] +[0, 1, 2] ``` Enumerate --------- ```python -for i, el in enumerate( [, i_start]): +for i, el in enumerate(, start=0): # Returns next element and its index on each pass. ... ``` Iterator -------- +**Potentially endless stream of elements.** + ```python - = iter() # `iter()` returns unmodified iterator. - = iter(, to_exclusive) # A sequence of return values until 'to_exclusive'. - = next( [, default]) # Raises StopIteration or returns 'default' on end. - = list() # Returns a list of iterator's remaining elements. + = iter() # `iter()` returns unmodified iterator. + = iter(, to_exclusive) # A sequence of return values until 'to_exclusive'. + = next( [, default]) # Raises StopIteration or returns 'default' on end. + = list() # Returns a list of iterator's remaining elements. ``` ### Itertools ```python -from itertools import count, repeat, cycle, chain, islice +import itertools as it ``` ```python - = count(start=0, step=1) # Returns updated value endlessly. Accepts floats. - = repeat( [, times]) # Returns element endlessly or 'times' times. - = cycle() # Repeats the sequence endlessly. + = it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats. + = it.repeat( [, times]) # Returns element endlessly or 'times' times. + = it.cycle() # Repeats the sequence endlessly. ``` ```python - = chain(, [, ...]) # Empties collections in order. - = chain.from_iterable() # Empties collections inside a collection in order. + = it.chain(, [, ...]) # Empties collections in order (figuratively). + = it.chain.from_iterable() # Empties collections inside a collection in order. ``` ```python - = islice(, to_exclusive) # Only returns first 'to_exclusive' elements. - = islice(, from_inclusive, …) # `to_exclusive, step_size`. + = it.islice(, to_exclusive) # Only returns first 'to_exclusive' elements. + = it.islice(, from_inc, …) # `to_exclusive, +step_size`. Indices can be None. ``` @@ -257,187 +266,188 @@ Type #### Some types do not have built-in names, so they must be imported: ```python -from types import FunctionType, MethodType, LambdaType, GeneratorType +from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType ``` ### Abstract Base Classes -**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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().** +**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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().** ```python ->>> from collections.abc import Sequence, Collection, Iterable +>>> from collections.abc import Iterable, Collection, Sequence >>> isinstance([1, 2, 3], Iterable) True ``` ```text +------------------+------------+------------+------------+ -| | Sequence | Collection | Iterable | +| | Iterable | Collection | Sequence | +------------------+------------+------------+------------+ | list, range, str | yes | yes | yes | -| dict, set | | yes | yes | -| iter | | | yes | +| dict, set | yes | yes | | +| iter | yes | | | +------------------+------------+------------+------------+ ``` ```python ->>> from numbers import Integral, Rational, Real, Complex, Number +>>> from numbers import Number, Complex, Real, Rational, Integral >>> isinstance(123, Number) True ``` ```text +--------------------+----------+----------+----------+----------+----------+ -| | Integral | Rational | Real | Complex | Number | +| | Number | Complex | Real | Rational | Integral | +--------------------+----------+----------+----------+----------+----------+ | int | yes | yes | yes | yes | yes | -| fractions.Fraction | | yes | yes | yes | yes | -| float | | | yes | yes | yes | -| complex | | | | yes | yes | -| decimal.Decimal | | | | | yes | +| fractions.Fraction | yes | yes | yes | yes | | +| float | yes | yes | yes | | | +| complex | yes | yes | | | | +| decimal.Decimal | yes | | | | | +--------------------+----------+----------+----------+----------+----------+ ``` String ------ +**Immutable sequence of characters.** + ```python = .strip() # Strips all whitespace characters from both ends. - = .strip('') # Strips all passed characters from both ends. + = .strip('') # Strips passed characters. Also lstrip/rstrip(). ``` ```python = .split() # Splits on one or more whitespace characters. - = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'. - = .join() # Joins elements using string as a separator. + = .split(sep=None, maxsplit=-1) # Splits on 'sep' string at most 'maxsplit' times. + = .splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n. + = .join() # Joins elements by using string as a separator. ``` ```python - = in # Checks if string contains a substring. + = in # Checks if string contains the substring. = .startswith() # Pass tuple of strings for multiple options. - = .endswith() # Pass tuple of strings for multiple options. = .find() # Returns start index of the first match or -1. - = .index() # Same but raises ValueError if missing. ``` ```python + = .lower() # Lowers the case. Also upper/capitalize/title(). + = .casefold() # Same, but converts ẞ/ß to ss, Σ/ς to σ, etc. = .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times. = .translate() # Use `str.maketrans()` to generate table. ``` ```python - = chr() # Converts int to Unicode char. - = ord() # Converts Unicode char to int. + = chr() # Converts passed integer to Unicode character. + = ord() # Converts passed Unicode character to integer. ``` -* **Also: `'lstrip()'`, `'rstrip()'`.** -* **Also: `'lower()'`, `'upper()'`, `'capitalize()'` and `'title()'`.** +* **Use `'unicodedata.normalize("NFC", )'` on strings like `'Motörhead'` before comparing them to other strings, because `'ö'` can be stored as one or two characters.** +* **`'NFC'` converts such characters to a single character, while `'NFD'` converts them to two.** ### Property Methods -```text -+---------------+----------+----------+----------+----------+----------+ -| | [ !#$%…] | [a-zA-Z] | [¼½¾] | [²³¹] | [0-9] | -+---------------+----------+----------+----------+----------+----------+ -| isprintable() | yes | yes | yes | yes | yes | -| isalnum() | | yes | yes | yes | yes | -| isnumeric() | | | yes | yes | yes | -| isdigit() | | | | yes | yes | -| isdecimal() | | | | | yes | -+---------------+----------+----------+----------+----------+----------+ +```python + = .isdecimal() # Checks for [0-9]. Also [०-९] and [٠-٩]. + = .isdigit() # Checks for [²³¹…] and isdecimal(). + = .isnumeric() # Checks for [¼½¾…], [零〇一…] and isdigit(). + = .isalnum() # Checks for [a-zA-Z…] and isnumeric(). + = .isprintable() # Checks for [ !#$%…] and isalnum(). + = .isspace() # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…]. ``` -* **Also: `'isspace()'` checks for `'[ \t\n\r\f\v…]'`.** Regex ----- +**Functions for regular expression matching.** + ```python import re - = re.sub(, new, text, count=0) # Substitutes all occurrences with 'new'. - = re.findall(, text) # Returns all occurrences as strings. - = re.split(, text, maxsplit=0) # Use brackets in regex to include the matches. - = re.search(, text) # Searches for first occurrence of the pattern. - = re.match(, text) # Searches only at the beginning of the text. - = re.finditer(, text) # Returns all occurrences as match objects. + = re.sub(r'', new, text, count=0) # Substitutes all occurrences with 'new'. + = re.findall(r'', text) # Returns all occurrences as strings. + = re.split(r'', text, maxsplit=0) # Add brackets around regex to keep matches. + = re.search(r'', text) # First occurrence of the pattern or None. + = re.match(r'', text) # Searches only at the beginning of the text. + = re.finditer(r'', text) # Returns all occurrences as Match objects. ``` -* **Search() and match() return None if they can't find a match.** +* **Raw string literals do not interpret escape sequences, thus enabling us to use regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12).** +* **Argument 'new' of re.sub() can be a function that accepts Match object and returns a str.** * **Argument `'flags=re.IGNORECASE'` can be used with all functions.** * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.** -* **Argument `'flags=re.DOTALL'` makes dot also accept the `'\n'`.** -* **Use `r'\1'` or `'\\1'` for backreference.** -* **Add `'?'` after an operator to make it non-greedy.** +* **Argument `'flags=re.DOTALL'` makes `'.'` also accept the `'\n'`.** +* **`'re.compile()'` returns a Pattern object with methods sub(), findall(), etc.** ### Match Object ```python - = .group() # Returns the whole match. Also group(0). - = .group(1) # Returns part in the first bracket. - = .groups() # Returns all bracketed parts. - = .start() # Returns start index of the match. - = .end() # Returns exclusive end index of the match. + = .group() # Returns the whole match. Also group(0). + = .group(1) # Returns part inside the first brackets. + = .groups() # Returns all bracketed parts as strings. + = .start() # Returns start index of the match. + = .end() # Returns exclusive end index of the match. ``` ### Special Sequences -* **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** -* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'`.** -* **Use a capital letter for negation.** ```python -'\d' == '[0-9]' # Matches decimal characters. -'\w' == '[a-zA-Z0-9_]' # Matches alphanumerics and underscore. -'\s' == '[ \t\n\r\f\v]' # Matches whitespaces. +'\d' == '[0-9]' # Also [०-९…]. Matches a decimal character. +'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches an alphanumeric or _. +'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches a whitespace. ``` +* **By default, decimal characters and alphanumerics from all alphabets are matched unless `'flags=re.ASCII'` is used. It restricts special sequence matches to the first 128 Unicode characters and also prevents `'\s'` from accepting `'\x1c'`, `'\x1d'`, `'\x1e'` and `'\x1f'` (non-printable characters that divide text into files, tables, rows and fields, respectively).** +* **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).** Format ------ -```python - = f'{}, {}' - = '{}, {}'.format(, ) +```perl + = f'{}, {}' # Curly brackets can also contain expressions. + = '{}, {}'.format(, ) # Or: '{0}, {a}'.format(, a=) + = '%s, %s' % (, ) # Redundant and inferior C-style formatting. ``` -### Attributes +### Example ```python ->>> from collections import namedtuple ->>> Person = namedtuple('Person', 'name height') +>>> Person = collections.namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) ->>> f'{person.height}' -'187' ->>> '{p.height}'.format(p=person) -'187' +>>> f'{person.name} is {person.height / 100} meters tall.' +'Jean-Luc is 1.87 meters tall.' ``` ### General Options ```python -{:<10} # ' ' -{:^10} # ' ' -{:>10} # ' ' -{:.<10} # '......' -{:0} # '' +{:<10} # ' ' +{:^10} # ' ' +{:>10} # ' ' +{:.<10} # '......' +{:0} # '' ``` -* **Use `'{:{}[...]}'` to set options dynamically.** -* **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** +* **Objects are rendered using `'format(, "")'`.** +* **Options can be generated dynamically: `f'{:{}[…]}'`.** +* **Adding `'='` to the expression prepends it to the output: `f'{1+1=}'` returns `'1+1=2'`.** +* **Adding `'!r'` to the expression converts object to string by calling its [repr()](#class) method.** ### Strings ```python -{'abcde'!r:10} # "'abcde' " -{'abcde':10.3} # 'abc ' -{'abcde':.3} # 'abc' +{'abcde':10} # 'abcde ' +{'abcde':10.3} # 'abc ' +{'abcde':.3} # 'abc' +{'abcde'!r:10} # "'abcde' " ``` ### Numbers ```python -{ 123456:10,} # ' 123,456' -{ 123456:10_} # ' 123_456' -{ 123456:+10} # ' +123456' -{-123456:=10} # '- 123456' -{ 123456: } # ' 123456' -{-123456: } # '-123456' +{123456:10} # ' 123456' +{123456:10,} # ' 123,456' +{123456:10_} # ' 123_456' +{123456:+10} # ' +123456' +{123456:=+10} # '+ 123456' +{123456: } # ' 123456' +{-123456: } # '-123456' ``` ### Floats ```python -{1.23456:10.3} # ' 1.23' -{1.23456:10.3f} # ' 1.235' -{1.23456:10.3e} # ' 1.235e+00' -{1.23456:10.3%} # ' 123.456%' +{1.23456:10.3} # ' 1.23' +{1.23456:10.3f} # ' 1.235' +{1.23456:10.3e} # ' 1.235e+00' +{1.23456:10.3%} # ' 123.456%' ``` #### Comparison of presentation types: @@ -454,6 +464,7 @@ Format | 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' | +--------------+----------------+----------------+----------------+----------------+ ``` + ```text +--------------+----------------+----------------+----------------+----------------+ | | {:.2} | {:.2f} | {:.2e} | {:.2%} | @@ -467,227 +478,227 @@ Format | 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' | +--------------+----------------+----------------+----------------+----------------+ ``` +* **`'{:g}'` is `'{:.6}'` with stripped zeros, exponent starting at `'1e+06'`.** * **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes `'{6.5:.0f}'` a `'6'` and `'{7.5:.0f}'` an `'8'`.** +* **This rule only effects numbers that can be represented exactly by a float (`.5`, `.25`, …).** ### Ints ```python -{90:c} # 'Z' -{90:b} # '1011010' -{90:X} # '5A' +{90:c} # 'Z'. Unicode character with value 90. +{90:b} # '1011010'. Binary representation of the int. +{90:X} # '5A'. Hexadecimal with upper-case letters. ``` Numbers ------- -### Types ```python - = int() # Or: math.floor() - = float() # Or: - = complex(real=0, imag=0) # Or: ± j - = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1) - = decimal.Decimal() # Or: Decimal((sign, digits, exponent)) + = int() # Or: math.trunc() + = float() # Or: + = complex(real=0, imag=0) # Or: ± j + = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1) + = decimal.Decimal() # Or: Decimal((sign, digits, exponent)) ``` * **`'int()'` and `'float()'` raise ValueError on malformed strings.** -* **Decimal numbers can be represented exactly, unlike floats where `'1.1 + 2.2 != 3.3'`.** +* **Decimal numbers are stored exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.** +* **Floats can be compared with: `'math.isclose(, )'`.** * **Precision of decimal operations is set with: `'decimal.getcontext().prec = '`.** +* **Bools can be used anywhere ints can, because bool is a subclass of int: `'True + 1 == 2'`.** -### Basic Functions +### Built-in Functions ```python - = pow(, ) # Or: ** - = abs() # = abs() - = round( [, ±ndigits]) # `round(126, -1) == 130` + = pow(, ) # Or: ** + = abs() # = abs() + = round( [, ±ndigits]) # Also math.floor/ceil(). + = min() # Also max(, [, ...]). + = sum() # Also math.prod(). ``` ### Math ```python -from math import e, pi, inf, nan, isinf, isnan -from math import sin, cos, tan, asin, acos, atan, degrees, radians -from math import log, log10, log2 +from math import pi, inf, nan, isnan # `inf*0` and `nan+1` return nan. +from math import sqrt, factorial # `sqrt(-1)` raises ValueError. +from math import sin, cos, tan # Also: asin, degrees, radians. +from math import log, log10, log2 # Log accepts base as second arg. ``` ### Statistics ```python -from statistics import mean, median, variance, stdev, pvariance, pstdev +from statistics import mean, median, mode # Also: variance, stdev, quantiles. ``` ### Random ```python -from random import random, randint, choice, shuffle, gauss, seed +from random import random, randint, uniform # Also: gauss, choice, shuffle, seed. +``` - = random() # A float inside [0, 1). - = randint(from_inc, to_inc) # An int inside [from_inc, to_inc]. - = choice() # Keeps the list intact. +```python + = random() # Returns a float inside [0, 1). + = randint/uniform(a, b) # Returns an int/float inside [a, b]. + = gauss(mean, stdev) # Also triangular(low, high, mode). + = choice() # Keeps it intact. Also sample(pop, k). +shuffle() # Shuffles the list in place. ``` -### Bin, Hex +### Hexadecimal Numbers ```python - = ±0b # Or: ±0x - = int('±', 2) # Or: int('±', 16) - = int('±0b', 0) # Or: int('±0x', 0) - = bin() # Returns '[-]0b'. + = ±0x # Or: ±0b + = int('±', 16) # Or: int('±', 2) + = int('±0x', 0) # Or: int('±0b', 0) + = hex() # Returns '[-]0x'. Also bin(). ``` ### Bitwise Operators ```python - = & # And - = | # Or - = ^ # Xor (0 if both bits equal) - = << n_bits # Left shift (>> for right) - = ~ # Not (also: - - 1) + = & # And (0b1100 & 0b1010 == 0b1000). + = | # Or (0b1100 | 0b1010 == 0b1110). + = ^ # Xor (0b1100 ^ 0b1010 == 0b0110). + = << n_bits # Left shift. Use >> for right. + = ~ # Not. Also - - 1. ``` Combinatorics ------------- -* **Every function returns an iterator.** -* **If you want to print the iterator, you need to pass it to the list() function first!** - ```python -from itertools import product, combinations, combinations_with_replacement, permutations +import itertools as it ``` ```python ->>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), ..., (1, 1, 1)] -``` - -```python ->>> product('abc', 'abc') # a b c +>>> list(it.product('abc', repeat=2)) # a b c [('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x ('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x ('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x ``` ```python ->>> combinations('abc', 2) # a b c +>>> list(it.permutations('abc', 2)) # a b c [('a', 'b'), ('a', 'c'), # a . x x - ('b', 'c')] # b . . x -``` - -```python ->>> combinations_with_replacement('abc', 2) # a b c -[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x - ('b', 'b'), ('b', 'c'), # b . x x - ('c', 'c')] # c . . x + ('b', 'a'), ('b', 'c'), # b x . x + ('c', 'a'), ('c', 'b')] # c x x . ``` ```python ->>> permutations('abc', 2) # a b c +>>> list(it.combinations('abc', 2)) # a b c [('a', 'b'), ('a', 'c'), # a . x x - ('b', 'a'), ('b', 'c'), # b x . x - ('c', 'a'), ('c', 'b')] # c x x . + ('b', 'c') # b . . x +] # c . . . ``` Datetime -------- -* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `
` classes. All are immutable and hashable.** -* **Time and datetime objects can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** -* **If object is naive, it is presumed to be in the system's timezone.** +**Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable.** ```python -from datetime import date, time, datetime, timedelta -from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary +# $ pip3 install python-dateutil +from datetime import date, time, datetime, timedelta, timezone +import zoneinfo, dateutil.tz ``` -### Constructors ```python - = date(year, month, day) - = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) -
= datetime(year, month, day, hour=0, minute=0, second=0, ...) -
= timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, - minutes=0, hours=0, weeks=0) + = date(year, month, day) # Only accepts valid dates from 1 to 9999 AD. + = time(hour=0, minute=0, second=0) # Also: `microsecond=0, tzinfo=None, fold=0`. +
= datetime(year, month, day, hour=0) # Also: `minute=0, second=0, microsecond=0, …`. +
= timedelta(weeks=0, days=0, hours=0) # Also: `minutes=0, seconds=0, microseconds=0`. ``` -* **Use `'.weekday()'` to get the day of the week (Mon == 0).** +* **Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!** * **`'fold=1'` means the second pass in case of time jumping back for one hour.** -* **`' = resolve_imaginary()'` fixes DTs that fall into the missing hour.** +* **Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns `'[±D, ]H:MM:SS[.…]'` and total_seconds() a float of all seconds.** +* **Use `'.weekday()'` to get the day of the week as an integer, with Monday being 0.** ### Now ```python - = D/DT.today() # Current local date or naive datetime. - = DT.utcnow() # Naive datetime from current UTC time. - = DT.now() # Aware datetime from current tz time. + = D/DT.today() # Current local date or naive DT. Also DT.now(). + = DT.now() # Aware DT from current time in passed timezone. ``` * **To extract time use `'.time()'`, `'.time()'` or `'.timetz()'`.** ### Timezone ```python - = UTC # UTC timezone. London without DST. - = tzlocal() # Local timezone. Also gettz(). - = gettz('/') # 'Continent/City_Name' timezone or None. - =
.astimezone() # Datetime, converted to the passed timezone. - = .replace(tzinfo=) # Unconverted object with a new timezone. + = timezone.utc # London without daylight saving time (DST). + = timezone() # Timezone with fixed offset from UTC. + = dateutil.tz.tzlocal() # Local timezone with dynamic offset from UTC. + = zoneinfo.ZoneInfo('') # 'Continent/City_Name' zone with dynamic offset. + =
.astimezone([]) # Converts DT to the passed or local fixed zone. + = .replace(tzinfo=) # Changes object's timezone without conversion. ``` +* **Timezones returned by tzlocal(), ZoneInfo() and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.** +* **To get ZoneInfo() to work on Windows run `'> pip3 install tzdata'`.** ### Encode ```python - = D/T/DT.fromisoformat('') # Object from ISO string. Raises ValueError. -
= DT.strptime(, '') # Datetime from str, according to format. - = D/DT.fromordinal() # D/DTn from days since the Gregorian NYE 1. - = DT.fromtimestamp() # Local time DTn from seconds since the Epoch. - = DT.fromtimestamp(, ) # Aware datetime from seconds since the Epoch. + = D/T/DT.fromisoformat() # Object from ISO string. Raises ValueError. +
= DT.strptime(, '') # Datetime from custom string. See Format. + = D/DT.fromordinal() # D/DT from days since the Gregorian NYE 1. + = DT.fromtimestamp() # Local naive DT from seconds since the Epoch. + = DT.fromtimestamp(, ) # Aware datetime from seconds since the Epoch. ``` -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by an arbitrary character. Offset is formatted as: `'HH:MM'`.** -* **Epoch on Unix systems is: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.mmmuuu[±HH:MM]'`, or both separated by an arbitrary character. All parts following the hours are optional.** +* **Python uses the Unix Epoch: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode ```python - = .isoformat(sep='T') # Also timespec='auto/hours/minutes/seconds'. - = .strftime('') # Custom string representation. + = .isoformat(sep='T') # Also `timespec='auto/hours/minutes/seconds/…'`. + = .strftime('') # Custom string representation of the object. = .toordinal() # Days since Gregorian NYE 1, ignoring time and tz. - = .timestamp() # Seconds since the Epoch, from DTn in local tz. - = .timestamp() # Seconds since the Epoch, from DTa. + = .timestamp() # Seconds since the Epoch, from local naive DT. + = .timestamp() # Seconds since the Epoch, from aware datetime. ``` ### Format ```python ->>> from datetime import datetime ->>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') ->>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z") -"Thursday, 14th of May '15, 11:39PM UTC+02:00" +>>> dt = datetime.strptime('2025-08-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') +>>> dt.strftime("%dth of %B '%y (%a), %I:%M %p %Z") +"14th of August '25 (Thu), 11:39 PM UTC+02:00" ``` -* **When parsing, `'%z'` also accepts `'±HH:MM'`.** -* **For abbreviated weekday and month use `'%a'` and `'%b'`.** +* **`'%z'` accepts `'±HH[:]MM'` and returns `'±HHMM'` or empty string if object is naive.** +* **`'%Z'` accepts `'UTC/GMT'` and local timezone's code and returns timezone's name, `'UTC[±HH:MM]'` if timezone is nameless, or an empty string if object is naive.** ### Arithmetics ```python - = ±
# Returned datetime can fall into missing hour. - = - # Returns the difference, ignoring time jumps. - = - # Ignores time jumps if they share tzinfo object. - = - # Convert DTs to UTC to get the actual delta. + = > # Ignores time jumps (fold attribute). Also ==. + = > # Ignores time jumps if they share tzinfo object. + = - # Ignores jumps. Convert to UTC for actual delta. + = - # Ignores jumps if they share tzinfo object. + = ± # Returned datetime can fall into missing hour. + = * # Also ` = abs()`, ` = ± `. + = / # Also `(, ) = divmod(, )`. ``` -Arguments ---------- -### Inside Function Call +Function +-------- +**Independent block of code that returns a value when called.** ```python -() # f(0, 0) -() # f(x=0, y=0) -(, ) # f(0, y=0) +def (): ... # E.g. `def func(x, y): ...`. +def (): ... # E.g. `def func(x=0, y=0): ...`. +def (, ): ... # E.g. `def func(x, y=0): ...`. ``` +* **Function returns None if it doesn't encounter `'return '` statement.** +* **Run `'global '` inside the function before assigning to global variable.** +* **Default values are evaluated when function is first encountered in the scope. Any mutation of a mutable default value will persist between invocations!** + +### Function Call -### Inside Function Definition ```python -def f(): # def f(x, y): -def f(): # def f(x=0, y=0): -def f(, ): # def f(x, y=0): + = () # E.g. `func(0, 0)`. + = () # E.g. `func(x=0, y=0)`. + = (, ) # E.g. `func(0, y=0)`. ``` Splat Operator -------------- -### Inside Function Call **Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.** ```python -args = (1, 2) -kwargs = {'x': 3, 'y': 4, 'z': 5} +args, kwargs = (1, 2), {'z': 3} func(*args, **kwargs) ``` #### Is the same as: ```python -func(1, 2, x=3, y=4, z=5) +func(1, 2, z=3) ``` ### Inside Function Definition @@ -702,44 +713,27 @@ def add(*a): 6 ``` -#### Legal argument combinations: -```python -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) -def f(*, x, y, z): # f(x=1, y=2, z=3) -def f(x, *, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) -def f(x, y, *, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) -``` - -```python -def f(*args): # f(1, 2, 3) -def f(x, *args): # f(1, 2, 3) -def f(*args, z): # f(1, 2, z=3) -def f(x, *args, z): # f(1, 2, z=3) -``` - -```python -def f(**kwargs): # f(x=1, y=2, z=3) -def f(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) -def f(*, x, **kwargs): # f(x=1, y=2, z=3) -``` - -```python -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) -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) -def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) -def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) +#### Allowed compositions of arguments and the ways they can be called: +```text ++---------------------------+--------------+--------------+----------------+ +| | func(1, 2) | func(1, y=2) | func(x=1, y=2) | ++---------------------------+--------------+--------------+----------------+ +| func(x, *args, **kwargs): | yes | yes | yes | +| func(*args, y, **kwargs): | | yes | yes | +| func(*, x, **kwargs): | | | yes | ++---------------------------+--------------+--------------+----------------+ ``` ### Other Uses ```python - = [* [, ...]] - = {* [, ...]} - = (*, [...]) - = {** [, ...]} + = [* [, ...]] # Or: list() [+ ...] + = (*, [...]) # Or: tuple() [+ ...] + = {* [, ...]} # Or: set() [| ...] + = {** [, ...]} # Or: | ... ``` ```python -head, *body, tail = +head, *body, tail = # Head or tail can be omitted. ``` @@ -747,72 +741,97 @@ Inline ------ ### Lambda ```python - = lambda: - = lambda , : + = lambda: # A single statement function. + = lambda , : # Also allows default arguments. ``` ### Comprehensions ```python - = [i+1 for i in range(10)] # [1, 2, ..., 10] - = {i for i in range(10) if i > 5} # {6, 7, 8, 9} - = (i+5 for i in range(10)) # (5, 6, ..., 14) - = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} + = [i+1 for i in range(10)] # Or: [1, 2, ..., 10] + = (i for i in range(10) if i > 5) # Or: iter([6, 7, 8, 9]) + = {i+5 for i in range(10)} # Or: {5, 6, ..., 14} + = {i: i*2 for i in range(10)} # Or: {0: 0, 1: 2, ..., 9: 18} ``` ```python ->>> [l+r for l in 'abc' for r in 'abc'] +>>> [l+r for l in 'abc' for r in 'abc'] # Inner loop is on the right side. ['aa', 'ab', 'ac', ..., 'cc'] ``` ### Map, Filter, Reduce ```python - = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) - = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) - = reduce(lambda out, x: out + x, range(10)) # 45 +from functools import reduce +``` + +```python + = map(lambda x: x + 1, range(10)) # Or: iter([1, 2, ..., 10]) + = filter(lambda x: x > 5, range(10)) # Or: iter([6, 7, 8, 9]) + = reduce(lambda out, x: out + x, range(10)) # Or: 45 ``` -* **Reduce must be imported from functools module.** ### Any, All ```python - = any() # False if empty. - = all(el[1] for el in ) # True if empty. + = any() # Is `bool()` True for any el? + = all() # True for all? Also True if empty. ``` ### Conditional Expression ```python - = if else + = if else # Only one expression is evaluated. ``` ```python ->>> [a if a else 'zero' for a in (0, 1, 2, 3)] +>>> [i if i else 'zero' for i in (0, 1, 2, 3)] # `any([0, '', [], None]) == False` ['zero', 1, 2, 3] ``` -### Namedtuple, Enum, Dataclass +### And, Or ```python -from collections import namedtuple -Point = namedtuple('Point', 'x y') -point = Point(0, 0) + = and [and ...] # Returns first false or last operand. + = or [or ...] # Returns first true or last operand. ``` +### Walrus Operator ```python -from enum import Enum -Direction = Enum('Direction', 'n e s w') -direction = Direction.n +>>> [i for a in '0123' if (i := int(a)) > 0] # Assigns to variable mid-sentence. +[1, 2, 3] ``` +### Named Tuple, Enum, Dataclass ```python +from collections import namedtuple +Point = namedtuple('Point', 'x y') # Creates tuple's subclass. +point = Point(0, 0) # Returns its instance. + +from enum import Enum +Direction = Enum('Direction', 'N E S W') # Creates Enum's subclass. +direction = Direction.N # Returns its member. + from dataclasses import make_dataclass -Creature = make_dataclass('Creature', ['loc', 'dir']) -creature = Creature(Point(0, 0), Direction.n) +Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class. +player = Player(point, direction) # Returns its instance. ``` +Imports +------- +**Mechanism that makes code in one file available to another file.** + +```python +import # Imports a built-in or '.py'. +import # Imports a built-in or '/__init__.py'. +import . # Imports a built-in or '/.py'. +``` +* **Package is a collection of modules, but it can also define its own objects.** +* **On a filesystem this corresponds to a directory of Python files with an optional init script.** +* **Running `'import '` does not automatically provide access to the package's modules unless they are explicitly imported in its init script.** +* **Directory of the file that is passed to python command serves as a root of local imports.** +* **For relative imports use `'from .[…][[.…]] import '`.** + + Closure ------- -**We have a closure in Python when:** -* **A nested function references a value of its enclosing function and then** -* **the enclosing function returns the nested function.** +**We have/get a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns its nested function.** ```python def get_multiplier(a): @@ -826,24 +845,23 @@ def get_multiplier(a): >>> multiply_by_3(10) 30 ``` - -* **If multiple nested functions within enclosing function reference the same value, that value gets shared.** -* **To dynamically access function's first free variable use `'.__closure__[0].cell_contents'`.** +* **Any value that is referenced from within multiple nested functions gets shared.** ### Partial ```python from functools import partial - = partial( [, , , ...]) + = partial( [, [, ...]]) ``` ```python ->>> import operator as op ->>> multiply_by_3 = partial(op.mul, 3) +>>> def multiply(a, b): +... return a * b +>>> multiply_by_3 = partial(multiply, 3) >>> multiply_by_3(10) 30 ``` -* **Partial is also useful in cases when function needs to be passed as an argument, because it enables us to set its arguments beforehand.** -* **A few examples being: `'defaultdict()'`, `'iter(, to_exclusive)'` and dataclass's `'field(default_factory=)'`.** +* **Partial is also useful in cases when a function needs to be passed as an argument because it enables us to set its arguments beforehand.** +* **A few examples being: `'defaultdict()'`, `'iter(, to_exc)'` and dataclass's `'field(default_factory=)'`.** ### Non-Local **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'.** @@ -867,7 +885,8 @@ def get_counter(): Decorator --------- -**A decorator takes a function, adds some functionality and returns it.** +* **A decorator takes a function, adds some functionality and returns it.** +* **It can be any [callable](#callable), but is usually implemented as a function that returns a [closure](#closure).** ```python @decorator_name @@ -876,7 +895,7 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example -**Decorator that prints function's name every time it gets called.** +**Decorator that prints function's name every time the function is called.** ```python from functools import wraps @@ -892,20 +911,20 @@ def debug(func): def add(x, y): return x + y ``` -* **Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).** -* **Without it `'add.__name__'` would return `'out'`.** +* **Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out). Without it, `'add.__name__'` would return `'out'`.** -### LRU Cache +### Cache **Decorator that caches function's return values. All function's arguments must be hashable.** ```python -from functools import lru_cache +from functools import cache -@lru_cache(maxsize=None) +@cache def fib(n): return n if n < 2 else fib(n-2) + fib(n-1) ``` -* **CPython interpreter limits recursion depth to 1000 by default. To increase it use `'sys.setrecursionlimit()'`.** +* **Potential problem with cache is that it can grow indefinitely. To clear stored values run `'.cache_clear()'`, or use `'@lru_cache(maxsize=)'` decorator instead.** +* **CPython interpreter limits recursion depth to 3000 by default. To increase it run `'sys.setrecursionlimit()'`.** ### Parametrized Decorator **A decorator that accepts arguments and returns a normal decorator that accepts a function.** @@ -926,124 +945,135 @@ def debug(print_result=False): def add(x, y): return x + y ``` +* **Using only `'@debug'` to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly.** Class ----- +**A template for creating user-defined objects.** + ```python -class : +class MyClass: def __init__(self, a): self.a = a + def __str__(self): + return str(self.a) def __repr__(self): class_name = self.__class__.__name__ return f'{class_name}({self.a!r})' - def __str__(self): - return str(self.a) @classmethod def get_class_name(cls): return cls.__name__ ``` -* **Return value of repr() should be unambiguous and of str() readable.** -* **If only repr() is defined, it will also be used for str().** -#### Str() use cases: ```python -print() -print(f'{}') -raise Exception() -loguru.logger.debug() -csv.writer().writerow([]) +>>> obj = MyClass(1) +>>> obj.a, str(obj), repr(obj) +(1, '1', 'MyClass(1)') ``` +* **Methods whose names start and end with two underscores are called special methods. They are executed when object is passed to a built-in function or used as an operand, for example, `'print(a)'` calls `'a.__str__()'` and `'a + b'` calls `'a.__add__(b)'`.** +* **Methods decorated with `'@staticmethod'` receive neither 'self' nor 'cls' argument.** +* **Return value of str() special method should be readable and of repr() unambiguous. If only repr() is defined, it will also be used for str().** -#### Repr() use cases: +#### Expressions that call the str() method: ```python -print([]) -print(f'{!r}') ->>> -loguru.logger.exception() -Z = dataclasses.make_dataclass('Z', ['a']); print(Z()) +print() +f'{}' +logging.warning() +csv.writer().writerow([]) ``` -### Constructor Overloading +#### Expressions that call the repr() method: ```python -class : - def __init__(self, a=None): - self.a = a +print/str/repr([]) +print/str/repr({: }) +f'{!r}' +Z = make_dataclass('Z', ['a']); print/str/repr(Z()) ``` -### Inheritance +### Subclass +* **Inheritance is a mechanism that enables a class to extend some other class (that is, subclass to extend its parent), and by doing so inherit all its methods and attributes.** +* **Subclass can then add its own methods and attributes or override inherited ones by reusing their names.** + ```python class Person: - def __init__(self, name, age): + def __init__(self, name): self.name = name - self.age = age + def __repr__(self): + return f'Person({self.name!r})' + def __lt__(self, other): + return self.name < other.name class Employee(Person): - def __init__(self, name, age, staff_num): - super().__init__(name, age) + def __init__(self, name, staff_num): + super().__init__(name) self.staff_num = staff_num + def __repr__(self): + return f'Employee({self.name!r}, {self.staff_num})' ``` -### Multiple Inheritance ```python -class A: pass -class B: pass -class C(A, B): pass +>>> people = {Person('Ann'), Employee('Bob', 0)} +>>> sorted(people) +[Person('Ann'), Employee('Bob', 0)] ``` -**MRO determines the order in which parent classes are traversed when searching for a method:** +### Type Annotations +* **They add type hints to variables, arguments and functions (`'def f() -> :'`).** +* **Hints are used by type checkers like [mypy](https://pypi.org/project/mypy/), data validation libraries such as [Pydantic](https://pypi.org/project/pydantic/) and lately also by [Cython](https://pypi.org/project/Cython/) compiler. However, they are not enforced by CPython interpreter.** ```python ->>> C.mro() -[, , , ] +from collections import abc + +: [| ...] [= ] +: list/set/abc.Iterable/abc.Sequence[] [= ] +: dict/tuple[, ...] [= ] ``` -### Property -**Pythonic way of implementing getters and setters.** +### Dataclass +**Decorator that uses class variables to generate init(), repr() and eq() special methods.** ```python -class MyClass: - @property - def a(self): - return self._a +from dataclasses import dataclass, field, make_dataclass - @a.setter - def a(self, value): - self._a = value +@dataclass(order=False, frozen=False) +class : + : + : = + : list/dict/set = field(default_factory=list/dict/set) ``` +* **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.** +* **For object to be [hashable](#hashable), all attributes must be hashable and 'frozen' must be True.** +* **Function field() is needed because `': list = []'` would make a list that is shared among all instances. Its 'default_factory' argument can be any [callable](#callable).** +* **For attributes of arbitrary type use `'typing.Any'`.** ```python ->>> el = MyClass() ->>> el.a = 123 ->>> el.a -123 +P = make_dataclass('P', ['x', 'y']) +P = make_dataclass('P', [('x', float), ('y', float)]) +P = make_dataclass('P', [('x', float, 0), ('y', float, 0)]) ``` -### Dataclass -**Decorator that automatically generates init(), repr() and eq() special methods.** +### Property +**Pythonic way of implementing getters and setters.** ```python -from dataclasses import dataclass, field +class Person: + @property + def name(self): + return ' '.join(self._name) -@dataclass(order=False, frozen=False) -class : - : - : = - : list/dict/set = field(default_factory=list/dict/set) + @name.setter + def name(self, value): + self._name = value.split() ``` -* **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.** -* **For object to be hashable, all attributes must be hashable and frozen must be True.** -* **Function field() is needed because `': list = []'` would make a list that is shared among all instances.** -* **Default_factory can be any [callable](#callable).** -#### Inline: ```python -from dataclasses import make_dataclass - = make_dataclass('', ) - = make_dataclass('', ) - = ('', [, ]) +>>> person = Person() +>>> person.name = '\t Guido van Rossum \n' +>>> person.name +'Guido van Rossum' ``` ### Slots -**Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.** +**Mechanism that restricts objects to attributes listed in 'slots'.** ```python class MyClassWithSlots: @@ -1055,9 +1085,7 @@ class MyClassWithSlots: ### Copy ```python from copy import copy, deepcopy - - = copy() - = deepcopy() + = copy/deepcopy() ``` @@ -1066,9 +1094,9 @@ Duck Types **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.** ### Comparable -* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.** -* **That means all objects compare not equal by default.** -* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.** +* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`. That means all user-defined objects compare not equal by default, because id() returns object's unique identification number (its memory address).** +* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.** +* **Ne() automatically works on any object that has eq() defined.** ```python class MyComparable: @@ -1081,9 +1109,8 @@ class MyComparable: ``` ### Hashable -* **Hashable object needs both hash() and eq() methods and its hash value should never change.** -* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.** -* **That is why Python automatically makes classes unhashable if you only implement eq().** +* **Hashable object needs both hash() and eq() methods and its hash value must not change.** +* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** ```python class MyHashable: @@ -1101,7 +1128,11 @@ class MyHashable: ``` ### Sortable -* **With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.** +* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods (used by <, >, <=, >=) and the rest will be automatically generated.** +* **Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.** +* **When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.** +* **To sort collection of strings in proper alphabetical order pass `'key=locale.strxfrm'` to sorted() after running `'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'`.** + ```python from functools import total_ordering @@ -1121,8 +1152,9 @@ class MySortable: ### Iterator * **Any object that has methods next() and iter() is an iterator.** -* **Next() should return next item or raise StopIteration.** -* **Iter() should return 'self'.** +* **Next() should return next item or raise StopIteration exception.** +* **Iter() should return an iterator of remaining items, i.e. 'self'.** +* **Any object that has iter() method can be used in a for loop.** ```python class Counter: def __init__(self): @@ -1148,7 +1180,8 @@ class Counter: ### Callable * **All functions and classes have a call() method, hence are callable.** -* **When this cheatsheet uses `''` as an argument, it actually means `''`.** +* **Use `'callable()'` or `'isinstance(, collections.abc.Callable)'` to check if object is callable. Calling an uncallable object raises TypeError.** +* **When this cheatsheet uses `''` as an argument, it means `''`.** ```python class Counter: def __init__(self): @@ -1165,10 +1198,11 @@ class Counter: ``` ### Context Manager +* **With statements only work on objects that have enter() and exit() special methods.** * **Enter() should lock the resources and optionally return an object.** -* **Exit() should release the resources.** +* **Exit() should release the resources (for example close a file).** * **Any exception that happens inside the with block is passed to the exit() method.** -* **If it wishes to suppress the exception it must return a true value.** +* **The exit() method can suppress the exception by returning a true value.** ```python class MyOpen: def __init__(self, filename): @@ -1213,9 +1247,9 @@ True ``` ### Collection -* **Only required methods are iter() and len().** +* **Only required methods are iter() and len(). Len() should return the number of items.** * **This cheatsheet actually means `''` when it uses `''`.** -* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.** +* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The main drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.** ```python class MyCollection: def __init__(self, a): @@ -1229,10 +1263,10 @@ class MyCollection: ``` ### Sequence -* **Only required methods are len() and getitem().** -* **Getitem() should return an item at index or raise IndexError.** +* **Only required methods are getitem() and len().** +* **Getitem() should return an item at the passed index or raise IndexError.** * **Iter() and contains() automatically work on any object that has getitem() defined.** -* **Reversed() automatically works on any object that has len() and getitem() defined.** +* **Reversed() automatically works on any object that has getitem() and len() defined. It returns reversed iterator of object's items.** ```python class MySequence: def __init__(self, a): @@ -1249,10 +1283,14 @@ class MySequence: return reversed(self.a) ``` +#### Discrepancies between glossary definitions and abstract base classes: +* **Python's glossary defines iterable as any object with special methods iter() and/or getitem() and sequence as any object with getitem() and len(). It doesn't define collection.** +* **Passing ABC Iterable to isinstance() or issubclass() only checks whether object/class has special method iter(), while ABC Collection checks for iter(), contains() and len().** + ### ABC Sequence * **It's a richer interface than the basic sequence.** * **Extending it generates iter(), contains(), reversed(), index() and count().** -* **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.** +* **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. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.** ```python from collections import abc @@ -1279,66 +1317,64 @@ class MyAbcSequence(abc.Sequence): | count() | | | | Yes | +------------+------------+------------+------------+--------------+ ``` -* **Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.** -* **Names of their required methods are stored in `'.__abstractmethods__'`.** +* **Method iter() is required for `'isinstance(, abc.Iterable)'` to return True, however any object with getitem() will work with any code expecting an iterable.** +* **MutableSequence, Set, MutableSet, Mapping and MutableMapping ABCs are also extendable. Use `'.__abstractmethods__'` to get names of required methods.** Enum ---- +**Class of named constants called members.** + ```python from enum import Enum, auto ``` ```python class (Enum): - = - = , - = auto() + = auto() # Increment of the last numeric value or 1. + = # Values don't have to be hashable. + = , # Values can be collections (this is a tuple). ``` -* **If there are no numeric values before auto(), it returns 1.** -* **Otherwise it returns an increment of the last numeric value.** +* **Methods receive the member they were called on as the 'self' argument.** +* **Accessing a member named after a reserved keyword causes SyntaxError.** ```python - = . # Returns a member. - = [''] # Returns a member or raises KeyError. - = () # Returns a member or raises ValueError. - = .name # Returns member's name. - = .value # Returns member's value. + = . # Returns a member. Raises AttributeError. + = [''] # Returns a member. Raises KeyError. + = () # Returns a member. Raises ValueError. + = .name # Returns member's name. + = .value # Returns member's value. ``` ```python -list_of_members = list() -member_names = [a.name for a in ] -member_values = [a.value for a in ] -random_member = random.choice(list()) + = list() # Returns enum's members. + = [a.name for a in ] # Returns enum's member names. + = [a.value for a in ] # Returns enum's member values. ``` ```python -def get_next_member(member): - members = list(member.__class__) - index = (members.index(member) + 1) % len(members) - return members[index] + = type() # Returns member's enum. + = itertools.cycle() # Returns endless iterator of members. + = random.choice(list()) # Returns a random member. ``` ### Inline ```python -Cutlery = Enum('Cutlery', 'fork knife spoon') -Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon']) -Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) +Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON') +Cutlery = Enum('Cutlery', ['FORK', 'KNIFE', 'SPOON']) +Cutlery = Enum('Cutlery', {'FORK': 1, 'KNIFE': 2, 'SPOON': 3}) ``` #### User-defined functions cannot be values, so they must be wrapped: ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), - 'OR' : partial(lambda l, r: l or r)}) + 'OR': partial(lambda l, r: l or r)}) ``` -* **Another solution in this particular case is to use functions and\_() and or\_() from the module [operator](#operator).** Exceptions ---------- -### Basic Example ```python try: @@ -1360,29 +1396,33 @@ finally: ``` * **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.** -* **Code inside the `'finally'` block will always be executed.** +* **Code inside the `'finally'` block will always be executed (unless a signal is received).** +* **All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try statement (only function block delimits scope).** +* **To catch signals use `'signal.signal(signal_number, )'`.** ### Catching Exceptions ```python -except : -except as : -except (, [...]): -except (, [...]) as : +except : ... +except as : ... +except (, [...]): ... +except (, [...]) as : ... ``` * **Also catches subclasses of the exception.** -* **Use `'traceback.print_exc()'` to print the error message to stderr.** +* **Use `'traceback.print_exc()'` to print the full error message to stderr.** * **Use `'print()'` to print just the cause of the exception (its arguments).** +* **Use `'logging.exception()'` to log the passed message, followed by the full error message of the caught exception. For details see [Logging](#logging).** +* **Use `'sys.exc_info()'` to get exception type, object, and traceback of caught exception.** ### Raising Exceptions ```python raise raise () -raise ( [, ...]) +raise ( [, ...]) ``` #### Re-raising caught exception: ```python -except as : +except [as ]: ... raise ``` @@ -1394,7 +1434,8 @@ exc_type = .__class__ filename = .__traceback__.tb_frame.f_code.co_filename func_name = .__traceback__.tb_frame.f_code.co_name line = linecache.getline(filename, .__traceback__.tb_lineno) -error_msg = ''.join(traceback.format_exception(exc_type, , .__traceback__)) +trace_str = ''.join(traceback.format_tb(.__traceback__)) +error_msg = ''.join(traceback.format_exception(type(), , .__traceback__)) ``` ### Built-in Exceptions @@ -1403,22 +1444,24 @@ BaseException +-- SystemExit # Raised by the sys.exit() function. +-- KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c). +-- Exception # User-defined exceptions should be derived from this class. - +-- ArithmeticError # Base class for arithmetic errors. - | +-- ZeroDivisionError # Raised when dividing by zero. - +-- AttributeError # Raised when an attribute is missing. - +-- EOFError # Raised by input() when it hits end-of-file condition. - +-- LookupError # Raised when a look-up on a collection fails. + +-- ArithmeticError # Base class for arithmetic errors such as ZeroDivisionError. + +-- AssertionError # Raised by `assert ` if expression returns false value. + +-- AttributeError # Raised when object doesn't have requested attribute/method. + +-- EOFError # Raised by input() when it hits an end-of-file condition. + +-- LookupError # Base class for errors when a collection can't find an item. | +-- IndexError # Raised when a sequence index is out of range. - | +-- KeyError # Raised when a dictionary key or set element is not found. - +-- NameError # Raised when a variable name is not found. - +-- OSError # Errors such as “file not found” or “disk full” (see Open). - | +-- FileNotFoundError # When a file or directory is requested but doesn't exist. + | +-- KeyError # Raised when a dictionary key or set element is missing. + +-- MemoryError # Out of memory. May be too late to start deleting variables. + +-- NameError # Raised when nonexistent name (variable/func/class) is used. + | +-- UnboundLocalError # Raised when local name is used before it's being defined. + +-- OSError # Errors such as FileExistsError/TimeoutError (see #Open). + | +-- ConnectionError # Errors such as BrokenPipeError/ConnectionAbortedError. +-- RuntimeError # Raised by errors that don't fall into other categories. - | +-- RecursionError # Raised when the maximum recursion depth is exceeded. - +-- StopIteration # Raised by next() when run on an empty iterator. - +-- TypeError # Raised when an argument is of wrong type. - +-- ValueError # When an argument is of right type but inappropriate value. - +-- UnicodeError # Raised when encoding/decoding strings to/from bytes fails. + | +-- NotImplementedEr… # Can be raised by abstract methods or by unfinished code. + | +-- RecursionError # Raised if max recursion depth is exceeded (3k by default). + +-- StopIteration # Raised when an empty iterator is passed to next(). + +-- TypeError # When an argument of the wrong type is passed to function. + +-- ValueError # When argument has the right type but inappropriate value. ``` #### Collections and their exceptions: @@ -1435,18 +1478,15 @@ BaseException #### Useful built-in exceptions: ```python -raise TypeError('Argument is of wrong type!') -raise ValueError('Argument is of right type but inappropriate value!') -raise RuntimeError('None of above!') +raise TypeError('Argument is of the wrong type!') +raise ValueError('Argument has the right type but an inappropriate value!') +raise RuntimeError('I am too lazy to define my own exception!') ``` ### User-defined Exceptions ```python -class MyError(Exception): - pass - -class MyInputError(MyError): - pass +class MyError(Exception): pass +class MyInputError(MyError): pass ``` @@ -1456,8 +1496,8 @@ Exit ```python import sys sys.exit() # Exits with exit code 0 (success). -sys.exit() # Prints to stderr and exits with 1. -sys.exit() # Exits with passed exit code. +sys.exit() # Exits with the passed exit code. +sys.exit() # Prints to stderr and exits with 1. ``` @@ -1467,26 +1507,25 @@ Print print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for messages about errors.** -* **Use `'flush=True'` to forcibly flush the stream.** +* **Stdout and stderr streams hold output in a buffer until they receive a string containing '\n' or '\r', buffer reaches 4096 characters, `'flush=True'` is used, or program exits.** ### Pretty Print ```python from pprint import pprint pprint(, width=80, depth=None, compact=False, sort_dicts=True) ``` -* **Levels deeper than 'depth' get replaced by '...'.** +* **Each item is printed on its own line if collection exceeds 'width' characters.** +* **Nested collections that are 'depth' levels deep get printed as '...'.** Input ----- -**Reads a line from user input or pipe if present.** - ```python - = input(prompt=None) + = input() ``` -* **Trailing newline gets stripped.** -* **Prompt string is printed to the standard output before reading input.** -* **Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.** +* **Reads a line from the user input or pipe if present (trailing newline gets stripped).** +* **If argument is passed, it gets printed to the standard output before input is read.** +* **EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if stream is already exhausted.** Command Line Arguments @@ -1500,42 +1539,41 @@ arguments = sys.argv[1:] ### Argument Parser ```python from argparse import ArgumentParser, FileType -p = ArgumentParser(description=) -p.add_argument('-', '--', action='store_true') # Flag -p.add_argument('-', '--', type=) # Option -p.add_argument('', type=, nargs=1) # First argument -p.add_argument('', type=, nargs='+') # Remaining arguments -p.add_argument('', type=, nargs='*') # Optional arguments -args = p.parse_args() # Exits on error. -value = args. +p = ArgumentParser(description=) # Returns a parser. +p.add_argument('-', '--', action='store_true') # Flag (defaults to False). +p.add_argument('-', '--', type=) # Option (defaults to None). +p.add_argument('', type=, nargs=1) # Mandatory first argument. +p.add_argument('', type=, nargs='+') # Mandatory remaining args. +p.add_argument('', type=, nargs='?/*') # Optional argument/s. +args = p.parse_args() # Exits on parsing error. + = args. # Returns `()`. ``` -* **Use `'help='` to set argument description.** -* **Use `'default='` to set the default value.** -* **Use `'type=FileType()'` for files.** +* **Use `'help='` to set argument description that will be displayed in help message.** +* **Use `'default='` to set option's or optional argument's default value.** +* **Use `'type=FileType()'` for files. Accepts 'encoding', but 'newline' is None.** Open ---- -**Opens the file and returns a corresponding file object.** +**Opens a file and returns the corresponding file object.** ```python = open(, mode='r', encoding=None, newline=None) ``` * **`'encoding=None'` means that the default encoding is used, which is platform dependent. Best practice is to use `'encoding="utf-8"'` whenever possible.** * **`'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.** -* **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.** +* **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on every '\n', '\r' and '\r\n'.** ### Modes -* **`'r'` - Read (default).** -* **`'w'` - Write (truncate).** +* **`'r'` - Read. Used by default.** +* **`'w'` - Write. Deletes existing contents.** * **`'x'` - Write or fail if the file already exists.** -* **`'a'` - Append.** -* **`'w+'` - Read and write (truncate).** +* **`'a'` - Append. Creates new file if it doesn't exist.** +* **`'w+'` - Read and write. Deletes existing contents.** * **`'r+'` - Read and write from the start.** * **`'a+'` - Read and write from the end.** -* **`'t'` - Text mode (default).** -* **`'b'` - Binary mode.** +* **`'b'` - Binary mode (`'rb'`, `'wb'`, `'xb'`, …).** ### Exceptions * **`'FileNotFoundError'` can be raised when reading with `'r'` or `'r+'`.** @@ -1548,7 +1586,7 @@ Open .seek(0) # Moves to the start of the file. .seek(offset) # Moves 'offset' chars/bytes from the start. .seek(0, 2) # Moves to the end of the file. -.seek(±offset, ) # Anchor: 0 start, 1 current position, 2 end. +.seek(±offset, origin) # Origin: 0 start, 1 current position, 2 end. ``` ```python @@ -1561,9 +1599,10 @@ Open ```python .write() # Writes a string or bytes object. .writelines() # Writes a coll. of strings or bytes objects. -.flush() # Flushes write buffer. +.flush() # Flushes write buffer. Runs every 4096/8192 B. +.close() # Closes the file after flushing write buffer. ``` -* **Methods do not add or strip trailing newlines, even writelines().** +* **Methods do not add or strip trailing newlines, not even writelines().** ### Read Text from File ```python @@ -1583,107 +1622,103 @@ def write_to_file(filename, text): Paths ----- ```python -from os import getcwd, path, listdir -from glob import glob +import os, glob +from pathlib import Path ``` ```python - = getcwd() # Returns the current working directory. - = path.join(, ...) # Joins two or more pathname components. - = path.abspath() # Returns absolute path. + = os.getcwd() # Returns working dir. Starts as shell's $PWD. + = os.path.join(, ...) # Joins two or more pathname components. + = os.path.realpath() # Resolves symlinks and calls path.abspath(). ``` ```python - = path.basename() # Returns final component of the path. - = path.dirname() # Returns path without the final component. - = path.splitext() # Splits on last period of the final component. + = os.path.basename() # Returns final component of the path. + = os.path.dirname() # Returns path without the final component. + = os.path.splitext() # Splits on last period of the final component. ``` ```python - = listdir(path='.') # Returns filenames located at path. - = glob('') # Returns paths matching the wildcard pattern. + = os.listdir(path='.') # Returns filenames located at the path. + = glob.glob('') # Returns paths matching the wildcard pattern. ``` ```python - = path.exists() # Or: .exists() - = path.isfile() # Or: .is_file() - = path.isdir() # Or: .is_dir() + = os.path.exists() # Or: .exists() + = os.path.isfile() # Or: .is_file() + = os.path.isdir() # Or: .is_dir() ``` -### DirEntry -**Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.** - ```python -from os import scandir + = os.stat() # Or: .stat() + = .st_mtime/st_size/… # Modification time, size in bytes, etc. ``` +### DirEntry +**Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir, and on Windows also stat information, thus significantly increasing the performance of code that requires it.** + ```python - = scandir(path='.') # Returns DirEntry objects located at path. - = .path # Returns whole path as a string. + = os.scandir(path='.') # Returns DirEntry objects located at the path. + = .path # Returns the whole path as a string. = .name # Returns final component as a string. - = open() # Opens the file and returns file object. + = open() # Opens the file and returns its file object. ``` ### Path Object ```python -from pathlib import Path -``` - -```python - = Path( [, ...]) # Accepts strings, Paths and DirEntry objects. - = / [/ ...] # One of the paths must be a Path object. + = Path( [, ...]) # Accepts strings, Paths, and DirEntry objects. + = / [/ ...] # First or second path must be a Path object. + = .resolve() # Returns absolute path with resolved symlinks. ``` ```python - = Path() # Returns relative cwd. Also Path('.'). - = Path.cwd() # Returns absolute cwd. Also Path().resolve(). - = Path.home() # Returns user's home directory. - = Path(__file__).resolve() # Returns script's path if cwd wasn't changed. + = Path() # Returns relative CWD. Also Path('.'). + = Path.cwd() # Returns absolute CWD. Also Path().resolve(). + = Path.home() # Returns user's home directory (absolute). + = Path(__file__).resolve() # Returns module's path if CWD wasn't changed. ``` ```python - = .parent # Returns Path without final component. + = .parent # Returns Path without the final component. = .name # Returns final component as a string. - = .stem # Returns final component without extension. - = .suffix # Returns final component's extension. + = .suffix # Returns name's last extension, e.g. '.py'. + = .stem # Returns name without the last extension. = .parts # Returns all components as strings. ``` ```python - = .iterdir() # Returns dir contents as Path objects. + = .iterdir() # Returns directory contents as Path objects. = .glob('') # Returns Paths matching the wildcard pattern. ``` ```python - = str() # Returns path as a string. - = open() # Opens the file and returns file object. + = str() # Returns path as string. Also .as_uri(). + = open() # Also .read/write_text/bytes(). ``` OS Commands ----------- -### Files and Directories -* **Paths can be either strings, Paths or DirEntry objects.** -* **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).** - ```python -import os, shutil +import os, shutil, subprocess ``` ```python -os.chdir() # Changes the current working directory. -os.mkdir(, mode=0o777) # Creates a directory. Mode is in octal. -os.makedirs(, mode=0o777) # Creates all directories in the path. +os.chdir() # Changes the current working directory (CWD). +os.mkdir(, mode=0o777) # Creates a directory. Permissions are in octal. +os.makedirs(, mode=0o777) # Creates all path's dirs. Also `exist_ok=False`. ``` ```python shutil.copy(from, to) # Copies the file. 'to' can exist or be a dir. +shutil.copy2(from, to) # Also copies creation and modification time. shutil.copytree(from, to) # Copies the directory. 'to' must not exist. ``` ```python os.rename(from, to) # Renames/moves the file or directory. -os.replace(from, to) # Same, but overwrites 'to' if it exists. +os.replace(from, to) # Same, but overwrites file 'to' even on Windows. +shutil.move(from, to) # Rename() that moves into 'to' if it's a dir. ``` ```python @@ -1691,17 +1726,19 @@ os.remove() # Deletes the file. os.rmdir() # Deletes the empty directory. shutil.rmtree() # Deletes the directory. ``` +* **Paths can be either strings, Path objects, or DirEntry objects.** +* **Functions report OS related errors by raising OSError or one of its [subclasses](#exceptions-1).** ### Shell Commands ```python -import os - = os.popen('').read() + = os.popen('') # Executes commands in sh/cmd. Returns combined stdout. + = .read(size=-1) # Reads 'size' chars or until EOF. Also readline/s(). + = .close() # Returns None if last command exited with returncode 0. ``` -#### Sends '1 + 1' to the basic calculator and captures its output: +#### Sends "1 + 1" to the basic calculator and captures its output: ```python ->>> from subprocess import run ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8') +>>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True) CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ``` @@ -1709,7 +1746,7 @@ CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ```python >>> from shlex import split >>> os.popen('echo 1 + 1 > test.in') ->>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w')) +>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w')) CompletedProcess(args=['bc', '-s'], returncode=0) >>> open('test.out').read() '2\n' @@ -1722,43 +1759,43 @@ JSON ```python import json - = json.dumps(, ensure_ascii=True, indent=None) - = json.loads() + = json.dumps() # Converts collection to JSON string. + = json.loads() # Converts JSON string to collection. ``` -### Read Object from JSON File +### Read Collection from JSON File ```python def read_json_file(filename): with open(filename, encoding='utf-8') as file: return json.load(file) ``` -### Write Object to JSON File +### Write Collection to JSON File ```python -def write_to_json_file(filename, an_object): +def write_to_json_file(filename, collection): with open(filename, 'w', encoding='utf-8') as file: - json.dump(an_object, file, ensure_ascii=False, indent=2) + json.dump(collection, file, ensure_ascii=False, indent=2) ``` Pickle ------ -**Binary file format for storing objects.** +**Binary file format for storing Python objects.** ```python import pickle - = pickle.dumps() - = pickle.loads() + = pickle.dumps() # Converts object to bytes object. + = pickle.loads() # Converts bytes object to object. ``` -### Read Object from File +### Read Object from Pickle File ```python def read_pickle_file(filename): with open(filename, 'rb') as file: return pickle.load(file) ``` -### Write Object to File +### Write Object to Pickle File ```python def write_to_pickle_file(filename, an_object): with open(filename, 'wb') as file: @@ -1778,9 +1815,12 @@ import csv ```python = csv.reader() # Also: `dialect='excel', delimiter=','`. = next() # Returns next row as a list of strings. - = list() # Returns list of remaining rows. + = list() # Returns a list of remaining rows. ``` -* **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** +* **File must be opened with a `'newline=""'` argument, or every '\r\n' sequence that is embedded inside a quoted field will get converted to '\n'!** +* **To print the spreadsheet to the console use [Tabulate](#table) library.** +* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.** +* **Reader accepts any collection of strings, not just files.** ### Write ```python @@ -1789,16 +1829,17 @@ import csv .writerows() # Appends multiple rows. ``` * **File must be opened with a `'newline=""'` argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!** +* **Open existing file with `'mode="a"'` to append to it or `'mode="w"'` to overwrite it.** ### Parameters -* **`'dialect'` - Master parameter that sets the default values.** -* **`'delimiter'` - A one-character string used to separate fields.** -* **`'quotechar'` - Character for quoting fields that contain special characters.** -* **`'doublequote'` - Whether quotechars inside fields get doubled or escaped.** -* **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped.** -* **`'lineterminator'` - Specifies how writer terminates rows.** -* **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.** -* **`'escapechar'` - Character for escaping 'quotechar' if 'doublequote' is False.** +* **`'dialect'` - Master parameter that sets the default values. String or a 'csv.Dialect' object.** +* **`'delimiter'` - A one-character string that separates fields (comma, tab, semicolon, etc.).** +* **`'lineterminator'` - How writer terminates rows. Reader looks for '\n', '\r' and '\r\n'.** +* **`'quotechar'` - Character for quoting fields containing delimiters, quotechars, '\n' or '\r'.** +* **`'escapechar'` - Character for escaping quotechars (not needed if doublequote is True).** +* **`'doublequote'` - Whether quotechars inside fields are/get doubled or escaped.** +* **`'quoting'` - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.** +* **`'skipinitialspace'` - Is space character at the start of the field stripped by the reader.** ### Dialects ```text @@ -1806,76 +1847,71 @@ import csv | | excel | excel-tab | unix | +------------------+--------------+--------------+--------------+ | delimiter | ',' | '\t' | ',' | +| lineterminator | '\r\n' | '\r\n' | '\n' | | quotechar | '"' | '"' | '"' | +| escapechar | None | None | None | | doublequote | True | True | True | -| skipinitialspace | False | False | False | -| lineterminator | '\r\n' | '\r\n' | '\n' | | quoting | 0 | 0 | 1 | -| escapechar | None | None | None | +| skipinitialspace | False | False | False | +------------------+--------------+--------------+--------------+ ``` ### Read Rows from CSV File ```python -def read_csv_file(filename): +def read_csv_file(filename, **csv_params): with open(filename, encoding='utf-8', newline='') as file: - return list(csv.reader(file)) + return list(csv.reader(file, **csv_params)) ``` ### Write Rows to CSV File ```python -def write_to_csv_file(filename, rows): - with open(filename, 'w', encoding='utf-8', newline='') as file: - writer = csv.writer(file) +def write_to_csv_file(filename, rows, mode='w', **csv_params): + with open(filename, mode, encoding='utf-8', newline='') as file: + writer = csv.writer(file, **csv_params) writer.writerows(rows) ``` SQLite ------ -**Server-less database engine that stores each database into a separate file.** +**A server-less database engine that stores each database into its own file.** -### Connect -**Opens a connection to the database file. Creates a new file if path doesn't exist.** ```python import sqlite3 - = sqlite3.connect() # Also ':memory:'. -.close() # Closes the connection. + = sqlite3.connect() # Opens existing or new file. Also ':memory:'. +.close() # Closes connection. Discards uncommitted data. ``` ### Read -**Returned values can be of type str, int, float, bytes or None.** ```python - = .execute('') # Can raise a subclass of sqlite3.Error. - = .fetchone() # Returns next row. Also next(). - = .fetchall() # Returns remaining rows. Also list(). + = .execute('') # Can raise a subclass of sqlite3.Error. + = .fetchone() # Returns next row. Also next(). + = .fetchall() # Returns remaining rows. Also list(). ``` ### Write ```python -.execute('') # Can raise a subclass of sqlite3.Error. -.commit() # Saves all changes since the last commit. -.rollback() # Discards all changes since the last commit. +.execute('') # Can raise a subclass of sqlite3.Error. +.commit() # Saves all changes since the last commit. +.rollback() # Discards all changes since the last commit. ``` #### Or: ```python -with : # Exits the block with commit() or rollback(), - .execute('') # depending on whether an exception occurred. +with : # Exits the block with commit() or rollback(), + .execute('') # depending on whether any exception occurred. ``` ### Placeholders -* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.** -* **Bools will be stored and returned as ints and dates as [ISO formatted strings](#encode).** ```python -.execute('', ) # Replaces '?'s in query with values. -.execute('', ) # Replaces ':'s with values. -.executemany('', ) # Runs execute() multiple times. +.execute('', ) # Replaces every question mark with an item. +.execute('', ) # Replaces every : with a value. +.executemany('', ) # Runs execute() multiple times. ``` +* **Passed values can be of type str, int, float, bytes, None, or bool (stored as 1 or 0).** ### Example -**In this example values are not actually saved because `'conn.commit()'` is omitted!** - +**Values are not actually saved in this example because `'conn.commit()'` is omitted!** ```python >>> conn = sqlite3.connect('test.db') >>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)') @@ -1883,46 +1919,56 @@ with : # Exits the block with commit() 1 >>> conn.execute('SELECT * FROM person').fetchall() [(1, 'Jean-Luc', 187)] -``` +``` -### MySQL -**Has a very similar interface, with differences listed below.** +### SQLAlchemy +**Library for interacting with various DB systems via SQL, method chaining, or ORM.** ```python -# $ pip3 install mysql-connector -from mysql import connector - = connector.connect(host=, …) # `user=, password=, database=`. - = .cursor() # Only cursor has execute method. -.execute('') # Can raise a subclass of connector.Error. -.execute('', ) # Replaces '%s's in query with values. -.execute('', ) # Replaces '%()s's with values. +# $ pip3 install sqlalchemy +from sqlalchemy import create_engine, text + = create_engine('') # Url: 'dialect://user:password@host/dbname'. + = .connect() # Creates a connection. Also .close(). + = .execute(text(''), …) # ``. Replaces every : with value. +with .begin(): ... # Exits the block with commit or rollback. +``` + +```text ++-----------------+--------------+----------------------------------+ +| Dialect | pip3 install | Dependencies | ++-----------------+--------------+----------------------------------+ +| mysql | mysqlclient | www.pypi.org/project/mysqlclient | +| postgresql | psycopg2 | www.pypi.org/project/psycopg2 | +| mssql | pyodbc | www.pypi.org/project/pyodbc | +| oracle+oracledb | oracledb | www.pypi.org/project/oracledb | ++-----------------+--------------+----------------------------------+ ``` Bytes ----- -**Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** +**A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python = b'' # Only accepts ASCII characters and \x00-\xff. - = [] # Returns int in range from 0 to 255. + = [index] # Returns an integer in range from 0 to 255. = [] # Returns bytes even if it has only one element. - = .join() # Joins elements using bytes as a separator. + = .join() # Joins elements by using bytes as a separator. ``` ### Encode ```python - = bytes() # Ints must be in range from 0 to 255. - = bytes(, 'utf-8') # Or: .encode('utf-8') + = bytes() # Integers must be in range from 0 to 255. + = bytes(, 'utf-8') # Encodes the string. Also .encode(). + = bytes.fromhex('') # Hex pairs can be separated by whitespaces. = .to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`. - = bytes.fromhex('') # Hex pairs can be separated by spaces. ``` ### Decode ```python - = list() # Returns ints in range from 0 to 255. - = str(, 'utf-8') # Or: .decode('utf-8') + = list() # Returns integers in range from 0 to 255. + = str(, 'utf-8') # Returns a string. Also .decode(). + = .hex() # Returns hex pairs. Accepts `sep=`. = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Returns a string of hexadecimal pairs. ``` ### Read Bytes from File @@ -1943,19 +1989,15 @@ def write_bytes(filename, bytes_obj): Struct ------ * **Module that performs conversions between a sequence of numbers and a bytes object.** -* **System’s type sizes and byte order are used by default.** +* **System’s type sizes, byte order, and alignment rules are used by default.** ```python -from struct import pack, unpack, iter_unpack -``` +from struct import pack, unpack -```python - = pack('', [, , ...]) - = unpack('', ) - = iter_unpack('', ) + = pack('', [, ...]) # Packs numbers according to format string. + = unpack('', ) # Use iter_unpack() to get iterator of tuples. ``` -### Example ```python >>> pack('>hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' @@ -1964,364 +2006,379 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ``` ### Format -#### For standard type sizes start format string with: -* **`'='` - system's byte order (usually little-endian)** -* **`'<'` - little-endian** -* **`'>'` - big-endian (also `'!'`)** +#### For standard type sizes and manual alignment (padding) start format string with: +* **`'='` - System's byte order (usually little-endian).** +* **`'<'` - Little-endian (i.e. least significant byte first).** +* **`'>'` - Big-endian (also `'!'`).** + +#### Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence: +* **`'c'` - A bytes object with a single element. For pad byte use `'x'`.** +* **`'s'` - A bytes object with n elements (not effected by byte order).** #### Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets: -* **`'x'` - pad byte** * **`'b'` - char (1/1)** * **`'h'` - short (2/2)** * **`'i'` - int (2/4)** * **`'l'` - long (4/4)** * **`'q'` - long long (8/8)** -#### Floating point types: +#### Floating point types (struct always uses standard sizes): * **`'f'` - float (4/4)** * **`'d'` - double (8/8)** Array ----- -**List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Sizes and byte order are always determined by the system.** +**List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.** ```python from array import array - = array('', ) # Array from collection of numbers. - = array('', ) # Array from bytes object. - = array('', ) # Treats array as a sequence of numbers. - = bytes() # Or: .tobytes() -.write() # Writes array to the binary file. +``` + +```python + = array('', ) # Creates array from collection of numbers. + = array('', ) # Writes passed bytes to array's memory. + = array('', ) # Treats passed array as a sequence of numbers. +.fromfile(, n_items) # Appends file's contents to array's memory. +``` + +```python + = bytes() # Returns a copy of array's memory. +.write() # Writes array's memory to the binary file. ``` Memory View ----------- -* **A sequence object that points to the memory of another object.** -* **Each element can reference a single or multiple consecutive bytes, depending on format.** -* **Order and number of elements can be changed with slicing.** -* **Casting only works between char and other types and uses system's sizes and byte order.** +**A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.** ```python - = memoryview() # Immutable if bytes, else mutable. - = [] # Returns an int or a float. - = [] # Mview with rearranged elements. - = .cast('') # Casts memoryview to the new format. -.release() # Releases the object's memory buffer. + = memoryview() # Immutable if bytes is passed, else mutable. + = [index] # Returns int/float. Bytes if format is 'c'. + = [] # Returns memoryview with rearranged elements. + = .cast('') # Only works between B/b/c and other types. +.release() # Releases memory buffer of the base object. ``` -### Decode ```python - = bytes() # Creates a new bytes object. - = .join() # Joins mviews using bytes object as sep. - = array('', ) # Treats mview as a sequence of numbers. -.write() # Writes mview to the binary file. + = bytes() # Returns a new bytes object. Also bytearray(). + = .join() # Joins memoryviews using bytes as a separator. + = array('', ) # Treats memoryview as a sequence of numbers. +.write() # Writes `bytes()` to the binary file. ``` ```python - = list() # Returns list of ints or floats. - = str(, 'utf-8') # Treats mview as a bytes object. - = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Treats mview as a bytes object. + = list() # Returns a list of ints, floats or bytes. + = str(, 'utf-8') # Treats memoryview as a bytes object. + = .hex() # Returns hex pairs. Accepts `sep=`. ``` Deque ----- -**A thread-safe list with efficient appends and pops from either side. Pronounced "deck".** +**List with efficient appends and pops from either side.** ```python from collections import deque - = deque(, maxlen=None) ``` ```python + = deque() # Use `maxlen=` to set size limit. .appendleft() # Opposite element is dropped if full. -.extendleft() # Collection gets reversed. - = .popleft() # Raises IndexError if empty. -.rotate(n=1) # Rotates elements to the right. +.extendleft() # Passed collection gets reversed. +.rotate(n=1) # Last element becomes first. + = .popleft() # Raises IndexError if deque is empty. ``` -Threading ---------- -* **CPython interpreter can only run a single thread at a time.** -* **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.** +Operator +-------- +**Module of functions that provide the functionality of operators. Functions are grouped by operator precedence, from least to most binding. Functions and operators in lines 1, 3 and 5 are also ordered by precedence within a group.** ```python -from threading import Thread, RLock, Semaphore, Event, Barrier -from concurrent.futures import ThreadPoolExecutor +import operator as op ``` -### Thread ```python - = Thread(target=) # Use `args=` to set the arguments. -.start() # Starts the thread. - = .is_alive() # Checks if the thread has finished executing. -.join() # Waits for the thread to finish. + = op.not_() # or, and, not (or/and missing) + = op.eq/ne/lt/ge/is_/is_not/contains(, ) # ==, !=, <, >=, is, is not, in + = op.or_/xor/and_(, ) # |, ^, & + = op.lshift/rshift(, ) # <<, >> + = op.add/sub/mul/truediv/floordiv/mod(, ) # +, -, *, /, //, % + = op.neg/invert() # -, ~ + = op.pow(, ) # ** + = op.itemgetter/attrgetter/methodcaller( [, ...]) # [index/key], .name, .name([…]) ``` -* **Use `'kwargs='` to pass keyword arguments to the function.** -* **Use `'daemon=True'`, or the program will not be able to exit while the thread is alive.** -### Lock ```python - = RLock() # Lock that can only be released by the owner. -.acquire() # Waits for the lock to be available. -.release() # Makes the lock available again. +elementwise_sum = map(op.add, list_a, list_b) +sorted_by_second = sorted(, key=op.itemgetter(1)) +sorted_by_both = sorted(, key=op.itemgetter(1, 0)) +first_element = op.methodcaller('pop', 0)() ``` +* **Most operators call the object's special method that is named after them (second object is passed as an argument), while logical operators call their own code that relies on bool().** +* **Comparisons can be chained: `'x < y < z'` gets converted to `'(x < y) and (y < z)`'.** + + +Match Statement +--------------- +**Executes the first block with matching pattern.** -#### Or: ```python -with : # Enters the block by calling acquire(), - ... # and exits it with release(). +match : + case [if ]: + + ... ``` -### Semaphore, Event, Barrier +### Patterns ```python - = Semaphore(value=1) # Lock that can be acquired by 'value' threads. - = Event() # Method wait() blocks until set() is called. - = Barrier(n_times) # Wait() blocks until it's called n_times. + = 1/'abc'/True/None/math.pi # Matches the literal or a dotted name. + = () # Matches any object of that type (or ABC). + = _ # Matches any object. Useful in last case. + = # Matches any object and binds it to name. + = as # Binds match to name. Also (). + = | [| ...] # Matches any of the patterns. + = [, ...] # Matches sequence with matching items. + = {: , ...} # Matches dictionary with matching items. + = (=, ...) # Matches object with matching attributes. ``` +* **Sequence pattern can also be written as a tuple, i.e. `'(, [...])'`.** +* **Use `'*'` and `'**'` in sequence/mapping patterns to bind remaining items.** +* **Sequence pattern must match all items of the collection, while mapping pattern does not.** +* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).** +* **Built-in types allow a single positional pattern that is matched against the entire object.** +* **All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.** -### Thread Pool Executor -**Object that manages thread execution.** +### Example ```python - = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as : …` -.shutdown(wait=True) # Blocks until all threads finish executing. +>>> from pathlib import Path +>>> match Path('/home/gto/python-cheatsheet/README.md'): +... case Path( +... parts=['/', 'home', user, *_] +... ) as p if p.name.lower().startswith('readme') and p.is_file(): +... print(f'{p.name} is a readme file that belongs to user {user}.') +README.md is a readme file that belongs to user gto. ``` + +Logging +------- ```python - = .map(, , ...) # A multithreaded and non-lazy map(). - = .submit(, , ...) # Starts a thread and returns its Future object. - = .done() # Checks if the thread has finished executing. - = .result() # Waits for thread to finish and returns result. +import logging as log ``` -### Queue -**A thread-safe FIFO queue. For LIFO queue use LifoQueue.** ```python -from queue import Queue - = Queue(maxsize=0) +log.basicConfig(filename=, level='DEBUG') # Configures the root logger (see Setup). +log.debug/info/warning/error/critical() # Sends message to the root logger. + = log.getLogger(__name__) # Returns logger named after the module. +.() # Sends message to the logger. +.exception() # Error() that appends caught exception. ``` +### Setup ```python -.put() # Blocks until queue stops being full. -.put_nowait() # Raises queue.Full exception if full. - = .get() # Blocks until queue stops being empty. - = .get_nowait() # Raises queue.Empty exception if empty. +log.basicConfig( + filename=None, # Logs to stderr or appends to file. + format='%(levelname)s:%(name)s:%(message)s', # Add '%(asctime)s' for local datetime. + level=log.WARNING, # Drops messages with lower priority. + handlers=[log.StreamHandler(sys.stderr)] # Uses FileHandler if filename is set. +) ``` - -Operator --------- -**Module of functions that provide the functionality of operators.** ```python -from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs -from operator import eq, ne, lt, le, gt, ge -from operator import and_, or_, xor, not_ -from operator import itemgetter, attrgetter, methodcaller + = log.Formatter('') # Creates a Formatter. + = log.FileHandler(, mode='a') # Creates a Handler. Also `encoding=None`. +.setFormatter() # Adds Formatter to the Handler. +.setLevel() # Processes all messages by default. +.addHandler() # Adds Handler to the Logger. +.setLevel() # What is sent to its/ancestors' handlers. +.propagate = # Cuts off ancestors' handlers if False. ``` +* **Parent logger can be specified by naming the child logger `'.'`.** +* **If logger doesn't have a set level, it inherits it from the first ancestor that does.** +* **Formatter also accepts: pathname, filename, funcName, lineno, thread and process.** +* **RotatingFileHandler creates and deletes files based on 'maxBytes', 'backupCount' args.** +* **An object with `'filter()'` method (or the method itself) can be added to loggers and handlers via addFilter(). Message is dropped if filter() returns a false value.** +#### Creates a logger that writes all messages to a file and sends them to the root's handler that prints warnings or higher: ```python -import operator as op -elementwise_sum = map(op.add, list_a, list_b) -sorted_by_second = sorted(, key=op.itemgetter(1)) -sorted_by_both = sorted(, key=op.itemgetter(1, 0)) -product_of_elems = functools.reduce(op.mul, ) -union_of_sets = functools.reduce(op.or_, ) -LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_}) -last_el = op.methodcaller('pop')() +>>> logger = log.getLogger('my_module') +>>> handler = log.FileHandler('test.log', encoding='utf-8') +>>> handler.setFormatter(log.Formatter('%(asctime)s %(levelname)s:%(name)s:%(message)s')) +>>> logger.addHandler(handler) +>>> logger.setLevel('DEBUG') +>>> log.basicConfig() +>>> log.root.handlers[0].setLevel('WARNING') +>>> logger.critical('Running out of disk space.') +CRITICAL:my_module:Running out of disk space. +>>> print(open('test.log').read()) +2023-02-07 23:21:01,430 CRITICAL:my_module:Running out of disk space. ``` Introspection ------------- -**Inspecting code at runtime.** - -### Variables ```python - = dir() # Names of local variables (incl. functions). - = vars() # Dict of local variables. Also locals(). - = globals() # Dict of global variables. + = dir() # Local names of variables, functions, classes and modules. + = vars() # Dict of local names and their objects. Also locals(). + = globals() # Dict of global names and their objects, e.g. __builtin__. ``` -### Attributes ```python - = dir() # Names of object's attributes (incl. methods). - = vars() # Dict of writable attributes. Also .__dict__. - = hasattr(, '') # Checks if getattr() raises an AttributeError. -value = getattr(, '') # Raises AttributeError if attribute is missing. -setattr(, '', value) # Only works on objects with __dict__ attribute. -delattr(, '') # Equivalent to `del .`. + = dir() # Returns names of object's attributes (including methods). + = vars() # Returns dict of writable attributes. Also .__dict__. + = hasattr(, '') # Checks if object possesses attribute with passed name. +value = getattr(, '') # Returns object's attribute or raises AttributeError. +setattr(, '', value) # Sets attribute. Only works on objects with __dict__ attr. +delattr(, '') # Deletes attribute from __dict__. Also `del .`. ``` -### Parameters ```python -from inspect import signature - = signature() # Function's Signature object. - = .parameters # Dict of function's Parameter objects. - = .name # Parameter's name. - = .kind # Member of ParameterKind enum. + = inspect.signature() # Returns a Signature object of the passed function. + = .parameters # Returns dict of Parameters. Also .return_annotation. + = .kind # Returns ParameterKind member (Parameter.KEYWORD_ONLY, …). + = .annotation # Returns Parameter.empty if missing. Also .default. ``` -Metaprogramming ---------------- -**Code that generates code.** - -### Type -**Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.** - +Threading +--------- +**CPython interpreter can only run a single thread at a time. Using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.** ```python - = type('', , ) +from threading import Thread, Lock, RLock, Semaphore, Event, Barrier +from concurrent.futures import ThreadPoolExecutor, as_completed ``` +### Thread ```python ->>> Z = type('Z', (), {'a': 'abcde', 'b': 12345}) ->>> z = Z() + = Thread(target=) # Use `args=` to set the arguments. +.start() # Starts the thread. Also .is_alive(). +.join() # Waits for the thread to finish executing. ``` +* **Use `'kwargs='` to pass keyword arguments to the function.** +* **Use `'daemon=True'`, or the program won't be able to exit while the thread is alive.** -### Meta Class -**A class that creates classes.** - +### Lock ```python -def my_meta_class(name, parents, attrs): - attrs['a'] = 'abcde' - return type(name, parents, attrs) + = Lock/RLock() # RLock can only be released by acquirer. +.acquire() # Waits for the lock to be available. +.release() # Makes the lock available again. ``` #### Or: ```python -class MyMetaClass(type): - def __new__(cls, name, parents, attrs): - attrs['a'] = 'abcde' - return type.__new__(cls, name, parents, attrs) +with : # Enters the block by calling acquire() and + ... # exits it with release(), even on error. ``` -* **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.** -* **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).** -* **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)`**).** -* **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.** - -### Metaclass Attribute -**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().** +### Semaphore, Event, Barrier ```python -class MyClass(metaclass=MyMetaClass): - b = 12345 + = Semaphore(value=1) # Lock that can be acquired by 'value' threads. + = Event() # Method wait() blocks until set() is called. + = Barrier(n_times) # Wait() blocks until it's called n times. ``` +### Queue ```python ->>> MyClass.a, MyClass.b -('abcde', 12345) + = queue.Queue(maxsize=0) # A thread-safe first-in-first-out queue. +.put() # Blocks until queue stops being full. +.put_nowait() # Raises queue.Full exception if full. + = .get() # Blocks until queue stops being empty. + = .get_nowait() # Raises queue.Empty exception if empty. ``` -### Type Diagram +### Thread Pool Executor ```python -type(MyClass) == MyMetaClass # MyClass is an instance of MyMetaClass. -type(MyMetaClass) == type # MyMetaClass is an instance of type. -``` - -```text -+-------------+-------------+ -| Classes | Metaclasses | -+-------------+-------------| -| MyClass --> MyMetaClass | -| | v | -| object -----> type <+ | -| | ^ +--+ | -| str ----------+ | -+-------------+-------------+ + = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as : ...` + = .map(, , ...) # Multithreaded and non-lazy map(). Keeps order. + = .submit(, , ...) # Creates a thread and returns its Future obj. +.shutdown() # Waits for all submitted threads to finish. ``` -### Inheritance Diagram ```python -MyClass.__base__ == object # MyClass is a subclass of object. -MyMetaClass.__base__ == type # MyMetaClass is a subclass of type. + = .done() # Checks if the thread has finished executing. + = .result(timeout=None) # Waits for thread to finish and returns result. + = .cancel() # Cancels or returns False if running/finished. + = as_completed() # `next()` returns next completed Future. ``` +* **Map() and as\_completed() also accept 'timeout'. It causes futures.TimeoutError when next() is called/blocking. Map() times from original call and as_completed() from first call to next(). As\_completed() fails if next() is called too late, even if all threads are done.** +* **Exceptions that happen inside threads are raised when map iterator's next() or Future's result() are called. Future's exception() method returns exception object or None.** +* **ProcessPoolExecutor provides true parallelism but: everything sent to/from workers must be [pickable](#pickle), queues must be sent using executor's 'initargs' and 'initializer' parameters, and executor should only be reachable via `'if __name__ == "__main__": ...'`.** -```text -+-------------+-------------+ -| Classes | Metaclasses | -+-------------+-------------| -| MyClass | MyMetaClass | -| v | v | -| object <----- type | -| ^ | | -| str | | -+-------------+-------------+ -``` +Coroutines +---------- +* **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.** +* **Coroutine definition starts with `'async'` and its call with `'await'`.** +* **Use `'asyncio.run()'` to start the first/main coroutine.** -Eval ----- ```python ->>> from ast import literal_eval ->>> literal_eval('[1, 2, 3]') -[1, 2, 3] ->>> literal_eval('1 + 2') -ValueError: malformed node or string +import asyncio as aio ``` +```python + = () # Creates a coroutine by calling async def function. + = await # Starts the coroutine and returns its result. + = aio.create_task() # Schedules the coroutine for execution. + = await # Returns coroutine's result. Also .cancel(). +``` -Coroutines ----------- -* **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.** -* **Coroutine definition starts with `'async'` and its call with `'await'`.** -* **`'asyncio.run()'` is the main entry point for asynchronous programs.** -* **Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.** -* **Asyncio module also provides its own [Queue](#queue), [Event](#semaphore-event-barrier), [Lock](#lock) and [Semaphore](#semaphore-event-barrier) classes.** +```python + = aio.gather(, ...) # Schedules coros. Returns list of results on await. + = aio.wait(, return_when=…) # `'ALL/FIRST_COMPLETED'`. Returns (done, pending). + = aio.as_completed() # Iter of coros that return next result on await. +``` #### Runs a terminal game where you control an asterisk that must avoid numbers: - ```python -import asyncio, collections, curses, enum, random +import asyncio, collections, curses, curses.textpad, enum, random -P = collections.namedtuple('P', 'x y') # Position -D = enum.Enum('D', 'n e s w') # Direction +P = collections.namedtuple('P', 'x y') # Position +D = enum.Enum('D', 'n e s w') # Direction +W, H = 15, 7 # Width, Height def main(screen): - curses.curs_set(0) # Makes cursor invisible. - screen.nodelay(True) # Makes getch() non-blocking. - asyncio.run(main_coroutine(screen)) # Starts running asyncio code. + curses.curs_set(0) # Makes cursor invisible. + screen.nodelay(True) # Makes getch() non-blocking. + asyncio.run(main_coroutine(screen)) # Starts running asyncio code. async def main_coroutine(screen): - state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}} moves = asyncio.Queue() - coros = (*(random_controller(id_, moves) for id_ in range(10)), - human_controller(screen, moves), - model(moves, state, *screen.getmaxyx()), - view(state, screen)) - await asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED) + state = {'*': P(0, 0)} | {id_: P(W//2, H//2) for id_ in range(10)} + ai = [random_controller(id_, moves) for id_ in range(10)] + mvc = [human_controller(screen, moves), model(moves, state), view(state, screen)] + tasks = [asyncio.create_task(coro) for coro in ai + mvc] + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) async def random_controller(id_, moves): while True: d = random.choice(list(D)) moves.put_nowait((id_, d)) - await asyncio.sleep(random.random() / 2) + await asyncio.sleep(random.triangular(0.01, 0.65)) async def human_controller(screen, moves): while True: - ch = screen.getch() - key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w} - if ch in key_mappings: - moves.put_nowait(('*', key_mappings[ch])) - await asyncio.sleep(0.01) + key_mappings = {258: D.s, 259: D.n, 260: D.w, 261: D.e} + if d := key_mappings.get(screen.getch()): + moves.put_nowait(('*', d)) + await asyncio.sleep(0.005) -async def model(moves, state, height, width): - while state['*'] not in {p for id_, p in state.items() if id_ != '*'}: +async def model(moves, state): + while state['*'] not in (state[id_] for id_ in range(10)): id_, d = await moves.get() - p = state[id_] deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)} - new_p = P(p.x + deltas[d].x, p.y + deltas[d].y) - if 0 <= new_p.x < width-1 and 0 <= new_p.y < height: - state[id_] = new_p + state[id_] = P((state[id_].x + deltas[d].x) % W, (state[id_].y + deltas[d].y) % H) async def view(state, screen): + offset = P(curses.COLS//2 - W//2, curses.LINES//2 - H//2) while True: - screen.clear() + screen.erase() + curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W) for id_, p in state.items(): - screen.addstr(p.y, p.x, str(id_)) - await asyncio.sleep(0.01) + screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H, + offset.x + (p.x - state['*'].x + W//2) % W, str(id_)) + screen.refresh() + await asyncio.sleep(0.005) if __name__ == '__main__': curses.wrapper(main) @@ -2336,10 +2393,9 @@ Progress Bar ------------ ```python # $ pip3 install tqdm ->>> from tqdm import tqdm ->>> from time import sleep ->>> for el in tqdm([1, 2, 3], desc='Processing'): -... sleep(1) +>>> import tqdm, time +>>> for el in tqdm.tqdm([1, 2, 3], desc='Processing'): +... time.sleep(1) Processing: 100%|████████████████████| 3/3 [00:03<00:00, 1.00s/it] ``` @@ -2349,243 +2405,242 @@ Plot ```python # $ pip3 install matplotlib import matplotlib.pyplot as plt -plt.plot(, [, label=]) # Or: plt.plot() -plt.legend() # Adds a legend. -plt.savefig() # Saves the figure. -plt.show() # Displays the figure. -plt.clf() # Clears the figure. + +plt.plot/bar/scatter(x_data, y_data [, label=]) # Also plt.plot(y_data). +plt.legend() # Adds a legend. +plt.title/xlabel/ylabel() # Adds a title or label. +plt.show() # Also plt.savefig(). +plt.clf() # Clears the plot. ``` Table ----- -#### Prints a CSV file as an ASCII table: +#### Prints a CSV spreadsheet to the console: ```python # $ pip3 install tabulate import csv, tabulate with open('test.csv', encoding='utf-8', newline='') as file: - rows = csv.reader(file) - header = [a.title() for a in next(rows)] - table = tabulate.tabulate(rows, header) - print(table) + rows = list(csv.reader(file)) +print(tabulate.tabulate(rows, headers='firstrow')) ``` -Curses ------- -#### Runs a basic file explorer in the terminal: +Console App +----------- +#### Runs a basic file explorer in the console: ```python -from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER -from os import listdir, path, chdir +# $ pip3 install windows-curses +import curses, os +from curses import A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT def main(screen): - ch, first, selected, paths = 0, 0, 0, listdir() - while ch != ascii.ESC: - height, _ = screen.getmaxyx() - screen.clear() - for y, a_path in enumerate(paths[first : first+height]): - screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y)) + ch, first, selected, paths = 0, 0, 0, os.listdir() + while ch != ord('q'): + height, width = screen.getmaxyx() + screen.erase() + for y, filename in enumerate(paths[first : first+height]): + color = A_REVERSE if filename == paths[selected] else 0 + screen.addnstr(y, 0, filename, width-1, color) ch = screen.getch() - selected += (ch == KEY_DOWN) - (ch == KEY_UP) - selected = max(0, min(len(paths)-1, selected)) - first += (first <= selected - height) - (first > selected) - if ch in [KEY_LEFT, KEY_RIGHT, KEY_ENTER, 10, 13]: + selected -= (ch == KEY_UP) and (selected > 0) + selected += (ch == KEY_DOWN) and (selected < len(paths)-1) + first -= (first > selected) + first += (first < selected-(height-1)) + if ch in [KEY_LEFT, KEY_RIGHT, ord('\n')]: new_dir = '..' if ch == KEY_LEFT else paths[selected] - if path.isdir(new_dir): - chdir(new_dir) - first, selected, paths = 0, 0, listdir() + if os.path.isdir(new_dir): + os.chdir(new_dir) + first, selected, paths = 0, 0, os.listdir() if __name__ == '__main__': - wrapper(main) + curses.wrapper(main) ``` -Logging +GUI App ------- -```python -# $ pip3 install loguru -from loguru import logger -``` +#### A weight converter GUI application: ```python -logger.add('debug_{time}.log', colorize=True) # Connects a log file. -logger.add('error_{time}.log', level='ERROR') # Another file for errors or higher. -logger.('A logging message.') +# $ pip3 install PySimpleGUI +import PySimpleGUI as sg + +text_box = sg.Input(default_text='100', enable_events=True, key='QUANTITY') +dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='UNIT') +label = sg.Text('100 kg is 220.462 lbs.', key='OUTPUT') +button = sg.Button('Close') +window = sg.Window('Weight Converter', [[text_box, dropdown], [label], [button]]) + +while True: + event, values = window.read() + if event in [sg.WIN_CLOSED, 'Close']: + break + try: + quantity = float(values['QUANTITY']) + except ValueError: + continue + unit = values['UNIT'] + factors = {'g': 0.001, 'kg': 1, 't': 1000} + lbs = quantity * factors[unit] / 0.45359237 + window['OUTPUT'].update(value=f'{quantity} {unit} is {lbs:g} lbs.') +window.close() ``` -* **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.** -### Exceptions -**Exception description, stack trace and values of variables are appended automatically.** +Scraping +-------- +#### Scrapes Python's URL and logo from its Wikipedia page: ```python -try: - ... -except : - logger.exception('An error happened.') +# $ pip3 install requests beautifulsoup4 +import requests, bs4, os + +response = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)') +document = bs4.BeautifulSoup(response.text, 'html.parser') +table = document.find('table', class_='infobox vevent') +python_url = table.find('th', text='Website').next_sibling.a['href'] +logo_url = table.find('img')['src'] +filename = os.path.basename(logo_url) +with open(filename, 'wb') as file: + file.write(requests.get(f'https:{logo_url}').content) +print(f'{python_url}, file://{os.path.abspath(filename)}') ``` -### Rotation -**Argument that sets a condition when a new log file is created.** +### Selenium +**Library for scraping websites with dynamic content.** ```python -rotation=||| +# $ pip3 install selenium +from selenium import webdriver + + = webdriver.Chrome/Firefox/Safari/Edge() # Opens a browser. Also .quit(). +.get('') # Also .implicitly_wait(seconds). + = .page_source # Returns HTML of fully rendered page. + = .find_element('css selector', …) # '#.[=""]…'. + = .find_elements('xpath', …) # '//[@=""]…'. See XPath. + = .get_attribute() # Property if exists. Also .text. +.click/clear() # Also .send_keys(). ``` -* **`''` - Max file size in bytes.** -* **`''` - Max age of a file.** -* **`'