diff --git a/README.md b/README.md index 001c1628..59efcbe2 100644 --- a/README.md +++ b/README.md @@ -21,37 +21,37 @@ Contents Main ---- ```python -if __name__ == '__main__': # Skips next line if file was imported. - main() # Runs `def main(): ...` function. +if __name__ == '__main__': # Skips indented lines of code if file was imported. + main() # Executes user-defined `def main(): ...` function. ``` List ---- ```python - = [, , ...] # Creates a list object. Also list(). + = [, , ...] # Creates a new list object. Also list(). ``` ```python - = [index] # First index is 0. Last -1. Allows assignments. + = [index] # First index is 0, last -1. Also `[i] = `. = [] # Also [from_inclusive : to_exclusive : ±step]. ``` ```python -.append() # Appends element to the end. Also += []. -.extend() # Appends elements to the end. Also += . +.append() # Appends element to the end. Also ` += []`. +.extend() # Appends multiple elements. Also ` += `. ``` ```python -.sort() # Sorts the elements in ascending order. -.reverse() # Reverses the order of list's elements. - = sorted() # Returns a new list with sorted elements. - = reversed() # Returns reversed iterator of elements. +.sort(reverse=False) # Sorts the elements of the list in ascending order. +.reverse() # Reverses the order of elements. Takes linear time. + = sorted() # Returns a new sorted list. Accepts `reverse=True`. + = reversed() # Returns reversed iterator. Also list(). ``` ```python - = max() # Returns largest element. Also min(, ...). - = sum() # Returns sum of elements. Also math.prod(). + = max() # Returns the largest element. Also min(, ...). + = sum() # Returns a sum of elements. Also math.prod(). ``` ```python @@ -65,46 +65,46 @@ flatter_list = list(itertools.chain.from_iterable()) * **This text uses the term collection instead of iterable. For rationale see [Collection](#collection).** ```python - = 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 passed index and moves the rest to the right. -.remove() # Removes first occurrence of the item or raises ValueError. -.clear() # Removes all list's items. Also works on dictionary and set. + = len() # Returns number of items. Also works on dict and set. + = .count() # Number of occurrences. Also `if in : ...`. + = .index() # Returns index of the first occ. or raises ValueError. + = .pop() # Removes and returns item from the end. Accepts index. +.insert(, ) # Inserts item at the index and shifts remaining items. +.remove() # Removes first occurrence of item. Raises ValueError. +.clear() # Removes all items. Also works on dictionary and set. ``` Dictionary ---------- ```python - = {key_1: val_1, key_2: val_2, ...} # Use `[key]` to get or set the value. + = {key_1: val_1, key_2: val_2, ...} # Use `[key]` to get or assign the value. ``` ```python - = .keys() # Collection of keys that reflects changes. - = .values() # Collection of values that reflects changes. + = .keys() # A collection of keys that reflects changes. + = .values() # A collection of values that reflects changes. = .items() # Coll. of key-value tuples that reflects chgs. ``` ```python -value = .get(key, default=None) # Returns default argument if key is missing. +value = .get(key, default=None) # Returns argument default if key is missing. value = .setdefault(key, default=None) # Returns and writes default if key is missing. - = collections.defaultdict() # Returns a dict with default value `()`. - = collections.defaultdict(lambda: 1) # Returns a dict with default value 1. + = collections.defaultdict() # Dict with automatic default value `()`. + = collections.defaultdict(lambda: 1) # Dictionary with automatic default value 1. ``` ```python = dict() # Creates a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Creates a dict from two collections. - = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys. + = dict(zip(keys, values)) # Creates a dictionary from two collections. + = dict.fromkeys(keys [, value]) # Creates a dictionary from collection of keys. ``` ```python .update() # Adds items. Replaces ones with matching keys. 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} # Filters the dictionary by specified keys. +{k: v for k, v in .items() if k in keys} # Returns a dict of items with specified keys. ``` ### Counter @@ -120,32 +120,32 @@ value = .pop(key) # Removes item or raises KeyErro Set --- ```python - = {, , ...} # Use `set()` for empty set. + = {, , ...} # Coll. of unique items. Also set(), set(). ``` ```python -.add() # Or: |= {} -.update( [, ...]) # Or: |= +.add() # Adds item to the set. Same as ` |= {}`. +.update( [, ...]) # Adds items to the set. Same as ` |= `. ``` ```python - = .union() # Or: | - = .intersection() # Or: & - = .difference() # Or: - - = .symmetric_difference() # Or: ^ - = .issubset() # Or: <= - = .issuperset() # Or: >= + = .union() # Returns a set of all items. Also | . + = .intersection() # Returns all shared items. Also & . + = .difference() # Returns set's unique items. Also - . + = .symmetric_difference() # Returns non-shared items. Also ^ . + = .issuperset() # Returns False if collection has unique items. + = .issubset() # Is collection a superset? Also <= . ``` ```python - = .pop() # Raises KeyError if empty. -.remove() # Raises KeyError if missing. -.discard() # Doesn't raise an error. + = .pop() # Removes and returns an item or raises KeyError. +.remove() # Removes the item or raises KeyError if missing. +.discard() # Same as remove() but it doesn't raise an error. ``` ### Frozen Set * **Is immutable and hashable.** -* **That means it can be used as a key in a dictionary or as an element in a set.** +* **That means it can be used as a key in a dictionary or as an item in a set.** ```python = frozenset() ``` @@ -155,9 +155,9 @@ Tuple ----- **Tuple is an immutable and hashable list.** ```python - = () # Empty tuple. - = (,) # Or: , - = (, [, ...]) # Or: , [, ...] + = () # Returns an empty tuple. Also tuple(), tuple(). + = (,) # Returns a tuple with single element. Same as `,`. + = (, [, ...]) # Returns a tuple. Same as `, [, ...]`. ``` ### Named Tuple @@ -177,9 +177,9 @@ Range ----- **Immutable and hashable sequence of integers.** ```python - = 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). + = range(stop) # I.e. range(to_exclusive). Integers from 0 to `stop-1`. + = range(start, stop) # I.e. range(from_inc, to_exc). From start to `stop-1`. + = range(start, stop, ±step) # I.e. range(from_inclusive, to_exclusive, ±step_size). ``` ```python @@ -201,7 +201,7 @@ Iterator **Potentially endless stream of elements.** ```python - = iter() # `iter()` returns unmodified iterator. + = iter() # Calling 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. @@ -214,7 +214,7 @@ import itertools as it ```python = it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats. - = it.repeat( [, times]) # Returns element endlessly or 'times' times. + = it.repeat( [, times]) # Returns passed element endlessly or 'times' times. = it.cycle() # Repeats the passed sequence of elements endlessly. ``` @@ -224,8 +224,8 @@ import itertools as it ``` ```python - = it.islice(, to_exclusive) # Only returns first 'to_exclusive' elements. - = it.islice(, from_inc, …) # `to_exclusive, +step_size`. Indices can be None. + = it.islice(, stop) # Only returns (i.e. yields) first 'stop' elements. + = it.islice(, start, stop) # Also accepts `+step`. Start and stop can be None. ``` @@ -250,13 +250,13 @@ def count(start, step): Type ---- -* **Everything is an object.** -* **Every object has a type.** +* **Everything in Python is an object.** +* **Every object has a certain type.** * **Type and class are synonymous.** ```python - = type() # Or: .__class__ - = isinstance(, ) # Or: issubclass(type(), ) + = type() # Returns object's type. Same as `.__class__`. + = isinstance(, ) # Same result as `issubclass(type(), )`. ``` ```python @@ -295,21 +295,24 @@ True ``` ```text -+--------------------+----------+----------+----------+----------+----------+ -| | 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 | | | | | -+--------------------+----------+----------+----------+----------+----------+ ++--------------------+-----------+-----------+----------+----------+----------+ +| | 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 | | | | | ++--------------------+-----------+-----------+----------+----------+----------+ ``` String ------ **Immutable sequence of characters.** +```python + = 'abc' # Also "abc". Interprets \n, \t, \x00-\xff, etc. +``` ```python = .strip() # Strips all whitespace characters from both ends. @@ -317,40 +320,39 @@ String ``` ```python - = .split() # Splits on one or more whitespace characters. + = .split() # Splits it on one or more whitespace characters. = .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. + = .join() # Joins items by using the string as a separator. ``` ```python - = in # Checks if string contains the substring. - = .startswith() # Pass tuple of strings for multiple options. + = in # Returns True if string contains the substring. + = .startswith() # Pass tuple of strings to give multiple options. = .find() # Returns start index of the first match or -1. ``` ```python = .lower() # Lowers the case. Also upper/capitalize/title(). - = .casefold() # Same, but converts ẞ/ß to ss, Σ/ς to σ, etc. + = .casefold() # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc. = .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times. - = .translate() # Use `str.maketrans()` to generate table. + = .translate(table) # Use `str.maketrans()` to generate table. ``` ```python - = chr() # Converts passed integer to Unicode character. - = ord() # Converts passed Unicode character to integer. + = chr() # Converts passed integer into Unicode character. + = ord() # Converts passed Unicode character into integer. ``` * **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 ```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…]. + = .isdecimal() # Checks all chars for [0-9]. Also [०-९], [٠-٩]. + = .isdigit() # Checks for [²³¹…] and isdecimal(). Also [፩-፱]. + = .isnumeric() # Checks for [¼½¾…] and isdigit(). Also [零〇一…]. + = .isalnum() # Checks for [ABC…] and isnumeric(). Also [ªµº…]. + = .isprintable() # Checks for [ !"#$…] and isalnum(). Also emojis. + = .isspace() # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…]. ``` @@ -484,7 +486,7 @@ Format ### Ints ```python -{90:c} # 'Z'. Unicode character with value 90. +{90:c} # 'Z'. Returns Unicode character with value 90. {90:b} # '1011010'. Binary representation of the int. {90:X} # '5A'. Hexadecimal with upper-case letters. ``` @@ -535,8 +537,8 @@ from random import random, randint, uniform # Also: gauss, choice, shuffle, s ``` ```python - = random() # Returns a float inside [0, 1). - = randint/uniform(a, b) # Returns an int/float inside [a, b]. + = random() # Select a random float from [0, 1). + = randint/uniform(a, b) # Select an int/float from [a, b]. = gauss(mean, stdev) # Also triangular(low, high, mode). = choice() # Keeps it intact. Also sample(p, n). shuffle() # Works on all mutable sequences. @@ -767,7 +769,7 @@ from functools import reduce ```python = map(lambda x: x + 1, range(10)) # Returns iter([1, 2, ..., 10]). = filter(lambda x: x > 5, range(10)) # Returns iter([6, 7, 8, 9]). - = reduce(lambda out, x: out + x, range(10)) # Returns 45. + = reduce(lambda out, x: out + x, range(10)) # Returns 45. Accepts 'initial'. ``` ### Any, All @@ -819,9 +821,9 @@ 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'. +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 functions, classes, etc.** * **On a filesystem this corresponds to a directory of Python files with an optional init script.** @@ -944,7 +946,7 @@ 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.** +* **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 how­ever manually check if the argument they received is a function and act accordingly.** Class @@ -1433,7 +1435,7 @@ filename = .__traceback__.tb_frame.f_code.co_filename func_name = .__traceback__.tb_frame.f_code.co_name line_str = linecache.getline(filename, .__traceback__.tb_lineno) trace_str = ''.join(traceback.format_tb(.__traceback__)) -error_msg = ''.join(traceback.format_exception(type(), , .__traceback__)) +error_msg = ''.join(traceback.format_exception(*sys.exc_info())) ``` ### Built-in Exceptions @@ -1445,16 +1447,16 @@ BaseException +-- 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. + +-- EOFError # Is 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 index of a sequence (list/str) is out of range. - | +-- KeyError # Raised when a dictionary key or set element is missing. + | +-- KeyError # Raised when a dictionary key or a 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 and ConnectionAbortedError. - +-- RuntimeError # Raised by errors that don't fall into other categories. + +-- RuntimeError # Is raised by errors that don't fit into other categories. | +-- 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 exhausted (empty) iterator is passed to next(). @@ -1476,8 +1478,8 @@ BaseException #### Useful built-in exceptions: ```python -raise TypeError('Argument is of the wrong type!') -raise ValueError('Argument has the right type but an inappropriate value!') +raise TypeError('Passed argument is of the wrong type!') +raise ValueError('Argument has the right type but its value is off!') raise RuntimeError('I am too lazy to define my own exception!') ``` @@ -1493,9 +1495,9 @@ Exit **Exits the interpreter by raising SystemExit exception.** ```python import sys -sys.exit() # Exits with exit code 0 (success). -sys.exit() # Exits with the passed exit code. -sys.exit() # Prints to stderr and exits with 1. +sys.exit() # Exits with exit code 0 (success). +sys.exit() # Exits with the passed exit code. +sys.exit() # Prints to stderr and exits with 1. ``` @@ -1542,7 +1544,7 @@ p.add_argument('-', '--', action='https://github.com/store_true') # Flag (defaul 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. +p.add_argument('', type=, nargs='?') # Optional argument. Also *. args = p.parse_args() # Exits on parsing error. = args. # Returns `()`. ``` @@ -1631,8 +1633,8 @@ from pathlib import Path ``` ```python - = os.path.basename() # Returns final component of the path. - = os.path.dirname() # Returns path without the final component. + = os.path.basename() # Returns path's final component, i.e. file/dir. + = os.path.dirname() # Returns path with its final component removed. = os.path.splitext() # Splits on last period of the final component. ``` @@ -1702,36 +1704,36 @@ import os, shutil, subprocess ``` ```python -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`. +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. +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 or moves the file or directory 'from'. -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. +os.rename(from, to) # Renames or moves the file or directory 'from'. +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 -os.remove() # Deletes the file. Or `pip3 install send2trash`. -os.rmdir() # Deletes the empty directory or raises OSError. -shutil.rmtree() # Deletes the directory and all of its contents. +os.remove() # Deletes the file. Or `pip3 install send2trash`. +os.rmdir() # Deletes the empty directory or raises OSError. +shutil.rmtree() # Deletes the directory and all of its contents. ``` * **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 - = 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. + = 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: @@ -1757,8 +1759,8 @@ JSON ```python import json - = json.dumps() # Converts collection to JSON string. - = json.loads() # Converts JSON string to collection. + = json.dumps() # Converts collection to JSON string. + = json.loads() # Converts JSON string to collection. ``` ### Read Collection from JSON File @@ -1782,8 +1784,8 @@ Pickle ```python import pickle - = pickle.dumps() # Converts object to bytes object. - = pickle.loads() # Converts bytes object to object. + = pickle.dumps() # Converts object to bytes object. + = pickle.loads() # Converts bytes object to object. ``` ### Read Object from Pickle File @@ -1816,16 +1818,16 @@ import csv = list() # Returns a list of all remaining rows. ``` * **Without the `'newline=""'` argument, every '\r\n' sequence that is embedded inside a quoted field will get converted to '\n'! For details about newline argument see [Open](#open).** -* **To print the spreadsheet to the console use [Tabulate](#table) or PrettyTable library.** -* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#fileformats) library.** -* **Reader accepts any iterator (or collection) of strings, not just files.** +* **To print the spreadsheet to the console use either [Tabulate](#table) or PrettyTable library.** +* **For XML and binary Excel files (extensions xlsx, xlsm and xlsb) use [Pandas](#fileformats) library.** +* **Reader accepts any iterator (or collection) of strings, not just text files.** ### Write ```python = open(, 'w', newline='') # Opens the CSV (text) file for writing. = csv.writer() # Also: `dialect='excel', delimiter=','`. .writerow() # Encodes each object using `str()`. -.writerows() # Appends multiple rows to the file. +.writerows() # Appends multiple rows to opened file. ``` * **If file is opened without the `'newline=""'` argument, '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings (i.e., newlines may get doubled on Windows)!** * **Open existing file with `'mode="a"'` to append to it or `'mode="w"'` to overwrite it.** @@ -1833,7 +1835,7 @@ import csv ### Parameters * **`'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'.** +* **`'lineterminator'` - Sets 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 instead of escaped.** @@ -1883,14 +1885,14 @@ import sqlite3 ### Read ```python - = .execute('') # Can raise a subclass of sqlite3.Error. + = .execute('') # Can raise a subclass of the sqlite3.Error. = .fetchone() # Returns the next row. Also next(). = .fetchall() # Returns remaining rows. Also list(). ``` ### Write ```python -.execute('') # Can raise a subclass of sqlite3.Error. +.execute('') # Can raise a subclass of the sqlite3.Error. .commit() # Saves all changes since the last commit. .rollback() # Discards all changes since the last commit. ``` @@ -1905,7 +1907,7 @@ with : # Exits the block with commit() o ```python .execute('', ) # Replaces every question mark with an item. .execute('', ) # Replaces every : with a matching value. -.executemany('', ) # Runs execute() once for each collection. +.executemany('', ) # Executes the query once for each collection. ``` * **Passed values can be of type str, int, float, bytes, None, or bool (stored as 1 or 0).** * **SQLite does not restrict columns to any type unless table is declared as strict.** @@ -1928,7 +1930,7 @@ 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. +with .begin(): ... # Exits the block with a commit or rollback. ``` ```text @@ -1948,10 +1950,10 @@ Bytes **A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python - = b'' # Only accepts ASCII characters and \x00-\xff. + = b'' # Only accepts ASCII chars and [\x00-\xff]. = [index] # Returns an integer in range from 0 to 255. - = [] # Returns bytes even if it has only one element. - = .join() # Joins elements by using bytes as a separator. + = [] # Returns bytes even if it has one element. + = .join() # Joins elements using bytes as a separator. ``` ### Encode @@ -1994,7 +1996,7 @@ Struct from struct import pack, unpack = pack('', [, ...]) # Packs numbers according to format string. - = unpack('', ) # Use iter_unpack() to get iterator of tuples. + = unpack('', ) # Use iter_unpack() to get iter of tuples. ``` ```python @@ -2028,22 +2030,22 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' Array ----- -**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 (by calling the byteswap() method).** +**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 sys­tem, however bytes of each element can be reversed (by calling the byteswap() method).** ```python from array import array ``` ```python - = array('', ) # Creates an array from collection of numbers. - = array('', ) # Writes passed bytes to the array's memory. - = array('', ) # Treats passed array as a sequence of numbers. -.fromfile(, n_items) # Appends file contents to the array's memory. + = array('' [, ]) # Creates array. Accepts collection of numbers. + = array('', ) # Copies passed bytes into the array's memory. + = array('', ) # Treats passed array as a sequence of numbers. +.fromfile(, n_items) # Appends file contents to the array's memory. ``` ```python - = bytes() # Returns a copy of array's memory as bytes. -.write() # Writes array's memory to the binary file. + = bytes() # Returns a copy of array's memory as bytes. +.write() # Appends array's memory to the binary file. ``` @@ -2052,24 +2054,24 @@ Memory View **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 is passed, else mutable. - = [index] # Returns ints/floats. 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. + = memoryview() # Returns mutable memoryview if array is passed. + = [index] # Returns an int/float. Bytes if format is 'c'. + = [] # Returns memoryview with rearranged elements. + = .cast('') # Only works between B/b/c and the other types. +.release() # Releases the memory buffer of the base object. ``` ```python - = 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. + = bytes() # Returns a new bytes object. Also bytearray(). + = .join() # Joins memoryviews using bytes as a separator. + = array('', ) # Treats passed mview as a sequence of numbers. +.write() # Appends `bytes()` to the binary file. ``` ```python - = list() # Returns a list of ints, floats or bytes. - = str(, 'utf-8') # Treats passed memoryview as a bytes object. - = .hex() # Returns hex pairs. Accepts `sep=`. + = list() # Returns list of ints, floats or bytes objects. + = str(, 'utf-8') # Treats passed memoryview as `bytes()`. + = .hex() # Returns hexadecimal pairs. Also `sep=`. ``` @@ -2082,11 +2084,11 @@ from collections import deque ``` ```python - = deque() # Use `maxlen=` to set size limit. -.appendleft() # Opposite element is dropped if full. -.extendleft() # Prepends reversed coll. to the deque. -.rotate(n=1) # Last element becomes the first one. - = .popleft() # Raises IndexError if deque is empty. + = deque() # Use `maxlen=` to set size limit. +.appendleft() # Opposite element is dropped if full. +.extendleft() # Prepends reversed coll. to the deque. +.rotate(n=1) # Last element becomes the first one. + = .popleft() # Raises IndexError if deque is empty. ``` @@ -2115,7 +2117,7 @@ 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)`'.** +* **Comparisons can be chained: `'x < y < z'` gets converted to `'(x < y) and (y < z)'`.** Match Statement @@ -2131,15 +2133,15 @@ match : ### Patterns ```python - = 1/'abc'/True/None/math.pi # Matches the literal or a dotted name. + = 1/'abc'/True/None/math.pi # Matches the literal or attribute's value. = () # 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 if any of listed patterns match. = [, ...] # Matches a sequence. All items must match. - = {: , ...} # Matches a dict that has matching items. - = (=, ...) # Matches an object if attributes match. + = {: , ...} # Matches a dict if it has matching items. + = (=, ...) # Matches object that has matching attrbs. ``` * **Sequence pattern can also be written as a tuple, either with or without the brackets.** * **Use `'*'` and `'**'` in sequence/mapping patterns to bind remaining items.** @@ -2176,20 +2178,20 @@ log.debug/info/warning/error/critical() # Sends passed message to the ### Setup ```python log.basicConfig( - filename=None, # Logs to stderr or appends to file. + filename=None, # Prints 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. + level=log.WARNING, # Drops messages with a lower priority. handlers=[log.StreamHandler(sys.stderr)] # Uses FileHandler if filename is set. ) ``` ```python - = log.Formatter('') # Formats messages according to format str. + = log.Formatter('') # Formats messages according to format. = log.FileHandler(, mode='a') # Appends to file. Also `encoding=None`. .setFormatter() # Only outputs bare messages by default. -.setLevel() # Prints or saves every message by default. +.setLevel() # Prints/saves every message by default. .addHandler() # Logger can have more than one handler. -.setLevel() # What is sent to its/ancestors' handlers. +.setLevel() # What's sent to its/ancestors' handlers. .propagate = # Cuts off ancestors' handlers if False. ``` * **Parent logger can be specified by naming the child logger `'.'`.** @@ -2225,7 +2227,7 @@ Introspection ```python = 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. + = hasattr(, '') # Checks if object possesses attribute of the passed name. value = getattr(, '') # Returns the object's attribute or raises AttributeError. setattr(, '', value) # Sets attribute. Only works on objects with __dict__ attr. delattr(, '') # Deletes attribute from __dict__. Also `del .`. @@ -2251,7 +2253,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed ```python = Thread(target=) # Use `args=` to set the arguments. .start() # Starts the thread. Also .is_alive(). -.join() # Waits for the thread to finish executing. +.join() # Waits until the thread has finished 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.** @@ -2273,16 +2275,16 @@ with : # Enters the block by calling met ```python = Semaphore(value=1) # Lock that can be acquired by 'value' threads. = Event() # Method wait() blocks until set() is called. - = Barrier() # Wait() blocks until it's called int times. + = Barrier() # Wait() blocks until it's called integer times. ``` ### Queue ```python = queue.Queue(maxsize=0) # A first-in-first-out queue. It's thread safe. -.put() # Call blocks until queue stops being full. +.put() # The call blocks until queue stops being full. .put_nowait() # Raises queue.Full exception if queue is full. - = .get() # Call blocks until queue stops being empty. - = .get_nowait() # Raises queue.Empty exception if it's empty. + = .get() # The call blocks until queue stops being empty. + = .get_nowait() # Raises queue.Empty exception if it is empty. ``` ### Thread Pool Executor @@ -2290,7 +2292,7 @@ with : # Enters the block by calling met = ThreadPoolExecutor(max_workers=None) # Also `with ThreadPoolExecutor() as : …`. = .map(, , ...) # Multithreaded and non-lazy map(). Keeps order. = .submit(, , ...) # Creates a thread and returns its Future obj. -.shutdown() # Waits for all threads to finish executing. +.shutdown() # Waits for all the threads to finish executing. ``` ```python @@ -2307,7 +2309,7 @@ with : # Enters the block by calling met 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 consume as much memory.** -* **Coroutine definition starts with `'async'` keyword and its call with `'await'`.** +* **Coroutine definition starts with `'async'` keyword and its call with `'await'` keyword.** * **Use `'asyncio.run()'` to start the first/main coroutine.** ```python @@ -2324,7 +2326,7 @@ import asyncio as aio ```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. + = aio.as_completed() # Iter of coros. Each returns next result on await. ``` #### Runs a terminal game where you control an asterisk that must avoid numbers: @@ -2977,7 +2979,7 @@ play_notes('83♩,81♪,,83♪,,78♪,,74♪,,78♪,,71♪,,,,83♪,,81♪,,83 Pygame ------ -#### Opes a window and draws a square that can be moved with arrow keys: +#### Opens a window and draws a square that can be moved with arrow keys: ```python # $ pip3 install pygame import pygame as pg @@ -3539,11 +3541,11 @@ cdef class : # Also `cdef struct
- +
@@ -107,26 +107,26 @@ -

#Main

if __name__ == '__main__':      # Skips next line if file was imported.
-    main()                      # Runs `def main(): ...` function.
+

#Main

if __name__ == '__main__':      # Skips indented lines of code if file was imported.
+    main()                      # Executes user-defined `def main(): ...` function.
 
-

#List

<list> = [<el_1>, <el_2>, ...]  # Creates a list object. Also list(<collection>).
+

#List

<list> = [<el_1>, <el_2>, ...]  # Creates a new list object. Also list(<collection>).
 
-
<el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
+
<el>   = <list>[index]          # First index is 0, last -1. Also `<list>[i] = <el>`.
 <list> = <list>[<slice>]        # Also <list>[from_inclusive : to_exclusive : ±step].
 
-
<list>.append(<el>)             # Appends element to the end. Also <list> += [<el>].
-<list>.extend(<collection>)     # Appends elements to the end. Also <list> += <coll>.
+
<list>.append(<el>)             # Appends element to the end. Also `<list> += [<el>]`.
+<list>.extend(<collection>)     # Appends multiple elements. Also `<list> += <coll>`.
 
-
<list>.sort()                   # Sorts the elements in ascending order.
-<list>.reverse()                # Reverses the order of list's elements.
-<list> = sorted(<collection>)   # Returns a new list with sorted elements.
-<iter> = reversed(<list>)       # Returns reversed iterator of elements.
+
<list>.sort(reverse=False)      # Sorts the elements of the list in ascending order.
+<list>.reverse()                # Reverses the order of elements. Takes linear time.
+<list> = sorted(<collection>)   # Returns a new sorted list. Accepts `reverse=True`.
+<iter> = reversed(<list>)       # Returns reversed iterator. Also list(<iterator>).
 
-
<el>  = max(<collection>)       # Returns largest element. Also min(<el_1>, ...).
-<num> = sum(<collection>)       # Returns sum of elements. Also math.prod(<coll>).
+
<el>  = max(<collection>)       # Returns the largest element. Also min(<el_1>, ...).
+<num> = sum(<collection>)       # Returns a sum of elements. Also math.prod(<coll>).
 
elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
 sorted_by_second = sorted(<collection>, key=lambda el: el[1])
@@ -138,34 +138,34 @@
 
  • Module operator has function itemgetter() that can replace listed lambdas.
  • This text uses the term collection instead of iterable. For rationale see Collection.
  • -
    <int> = len(<list>)             # Returns number of items. Also works on dict, set and string.
    -<int> = <list>.count(<el>)      # Returns number of occurrences. Also `if <el> in <coll>: ...`.
    -<int> = <list>.index(<el>)      # Returns index of the first occurrence or raises ValueError.
    -<el>  = <list>.pop()            # Removes and returns item from the end or at index if passed.
    -<list>.insert(<int>, <el>)      # Inserts item at passed index and moves the rest to the right.
    -<list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
    -<list>.clear()                  # Removes all list's items. Also works on dictionary and set.
    +
    <int> = len(<list>)             # Returns number of items. Also works on dict and set.
    +<int> = <list>.count(<el>)      # Number of occurrences. Also `if <el> in <coll>: ...`.
    +<int> = <list>.index(<el>)      # Returns index of the first occ. or raises ValueError.
    +<el>  = <list>.pop()            # Removes and returns item from the end. Accepts index.
    +<list>.insert(<int>, <el>)      # Inserts item at the index and shifts remaining items.
    +<list>.remove(<el>)             # Removes first occurrence of item. Raises ValueError.
    +<list>.clear()                  # Removes all items. Also works on dictionary and set.
     
    -

    #Dictionary

    <dict> = {key_1: val_1, key_2: val_2, ...}      # Use `<dict>[key]` to get or set the value.
    +

    #Dictionary

    <dict> = {key_1: val_1, key_2: val_2, ...}      # Use `<dict>[key]` to get or assign the value.
     
    -
    <view> = <dict>.keys()                          # Collection of keys that reflects changes.
    -<view> = <dict>.values()                        # Collection of values that reflects changes.
    +
    <view> = <dict>.keys()                          # A collection of keys that reflects changes.
    +<view> = <dict>.values()                        # A collection of values that reflects changes.
     <view> = <dict>.items()                         # Coll. of key-value tuples that reflects chgs.
     
    -
    value  = <dict>.get(key, default=None)          # Returns default argument if key is missing.
    +
    value  = <dict>.get(key, default=None)          # Returns argument default if key is missing.
     value  = <dict>.setdefault(key, default=None)   # Returns and writes default if key is missing.
    -<dict> = collections.defaultdict(<type>)        # Returns a dict with default value `<type>()`.
    -<dict> = collections.defaultdict(lambda: 1)     # Returns a dict with default value 1.
    +<dict> = collections.defaultdict(<type>)        # Dict with automatic default value `<type>()`.
    +<dict> = collections.defaultdict(lambda: 1)     # Dictionary with automatic default value 1.
     
    <dict> = dict(<collection>)                     # Creates a dict from coll. of key-value pairs.
    -<dict> = dict(zip(keys, values))                # Creates a dict from two collections.
    -<dict> = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.
    +<dict> = dict(zip(keys, values))                # Creates a dictionary from two collections.
    +<dict> = dict.fromkeys(keys [, value])          # Creates a dictionary from collection of keys.
     
    <dict>.update(<dict>)                           # Adds items. Replaces ones with matching keys.
     value = <dict>.pop(key)                         # Removes item or raises KeyError if missing.
     {k for k, v in <dict>.items() if v == value}    # Returns set of keys that point to the value.
    -{k: v for k, v in <dict>.items() if k in keys}  # Filters the dictionary by specified keys.
    +{k: v for k, v in <dict>.items() if k in keys}  # Returns a dict of items with specified keys.
     

    Counter

    >>> from collections import Counter
     >>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red'])
    @@ -174,33 +174,33 @@
     [('blue', 3), ('red', 2), ('yellow', 1)]
     
    -

    #Set

    <set> = {<el_1>, <el_2>, ...}                   # Use `set()` for empty set.
    +

    #Set

    <set> = {<el_1>, <el_2>, ...}                # Coll. of unique items. Also set(), set(<coll>).
     
    -
    <set>.add(<el>)                                 # Or: <set> |= {<el>}
    -<set>.update(<collection> [, ...])              # Or: <set> |= <set>
    +
    <set>.add(<el>)                              # Adds item to the set. Same as `<set> |= {<el>}`.
    +<set>.update(<collection> [, ...])           # Adds items to the set. Same as `<set> |= <set>`.
     
    -
    <set>  = <set>.union(<coll.>)                   # Or: <set> | <set>
    -<set>  = <set>.intersection(<coll.>)            # Or: <set> & <set>
    -<set>  = <set>.difference(<coll.>)              # Or: <set> - <set>
    -<set>  = <set>.symmetric_difference(<coll.>)    # Or: <set> ^ <set>
    -<bool> = <set>.issubset(<coll.>)                # Or: <set> <= <set>
    -<bool> = <set>.issuperset(<coll.>)              # Or: <set> >= <set>
    +
    <set>  = <set>.union(<coll>)                 # Returns a set of all items. Also <set> | <set>.
    +<set>  = <set>.intersection(<coll>)          # Returns all shared items. Also <set> & <set>.
    +<set>  = <set>.difference(<coll>)            # Returns set's unique items. Also <set> - <set>.
    +<set>  = <set>.symmetric_difference(<coll>)  # Returns non-shared items. Also <set> ^ <set>.
    +<bool> = <set>.issuperset(<coll>)            # Returns False if collection has unique items.
    +<bool> = <set>.issubset(<coll>)              # Is collection a superset? Also <set> <= <set>.
     
    -
    <el> = <set>.pop()                              # Raises KeyError if empty.
    -<set>.remove(<el>)                              # Raises KeyError if missing.
    -<set>.discard(<el>)                             # Doesn't raise an error.
    +
    <el> = <set>.pop()                           # Removes and returns an item or raises KeyError.
    +<set>.remove(<el>)                           # Removes the item or raises KeyError if missing.
    +<set>.discard(<el>)                          # Same as remove() but it doesn't raise an error.
     

    Frozen Set

    • Is immutable and hashable.
    • -
    • That means it can be used as a key in a dictionary or as an element in a set.
    • +
    • That means it can be used as a key in a dictionary or as an item in a set.
    <frozenset> = frozenset(<collection>)
     
    -

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()                               # Empty tuple.
    -<tuple> = (<el>,)                          # Or: <el>,
    -<tuple> = (<el_1>, <el_2> [, ...])         # Or: <el_1>, <el_2> [, ...]
    +

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()                        # Returns an empty tuple. Also tuple(), tuple(<coll>).
    +<tuple> = (<el>,)                   # Returns a tuple with single element. Same as `<el>,`.
    +<tuple> = (<el_1>, <el_2> [, ...])  # Returns a tuple. Same as `<el_1>, <el_2> [, ...]`.
     
    @@ -214,9 +214,9 @@
    -

    #Range

    Immutable and hashable sequence of integers.

    <range> = range(stop)                      # I.e. range(to_exclusive).
    -<range> = range(start, stop)               # I.e. range(from_inclusive, to_exclusive).
    -<range> = range(start, stop, ±step)        # I.e. range(from_inclusive, to_exclusive, ±step).
    +

    #Range

    Immutable and hashable sequence of integers.

    <range> = range(stop)                # I.e. range(to_exclusive). Integers from 0 to `stop-1`.
    +<range> = range(start, stop)         # I.e. range(from_inc, to_exc). From start to `stop-1`.
    +<range> = range(start, stop, ±step)  # I.e. range(from_inclusive, to_exclusive, ±step_size).
     
    @@ -227,7 +227,7 @@ ...
    -

    #Iterator

    Potentially endless stream of elements.

    <iter> = iter(<collection>)                # `iter(<iter>)` returns unmodified iterator.
    +

    #Iterator

    Potentially endless stream of elements.

    <iter> = iter(<collection>)                # Calling iter(<iter>) returns unmodified iterator.
     <iter> = iter(<function>, to_exclusive)    # A sequence of return values until 'to_exclusive'.
     <el>   = next(<iter> [, default])          # Raises StopIteration or returns 'default' on end.
     <list> = list(<iter>)                      # Returns a list of iterator's remaining elements.
    @@ -238,14 +238,14 @@
     
    <iter> = it.count(start=0, step=1)         # Returns updated value endlessly. Accepts floats.
    -<iter> = it.repeat(<el> [, times])         # Returns element endlessly or 'times' times.
    +<iter> = it.repeat(<el> [, times])         # Returns passed element endlessly or 'times' times.
     <iter> = it.cycle(<collection>)            # Repeats the passed sequence of elements endlessly.
     
    <iter> = it.chain(<coll>, <coll> [, ...])  # Empties collections in order (only figuratively).
     <iter> = it.chain.from_iterable(<coll>)    # Empties collections inside a collection in order.
     
    -
    <iter> = it.islice(<coll>, to_exclusive)   # Only returns first 'to_exclusive' elements.
    -<iter> = it.islice(<coll>, from_inc, …)    # `to_exclusive, +step_size`. Indices can be None.
    +
    <iter> = it.islice(<coll>, stop)           # Only returns (i.e. yields) first 'stop' elements.
    +<iter> = it.islice(<coll>, start, stop)    # Also accepts `+step`. Start and stop can be None.
     

    #Generator

    • Any function that contains a yield statement returns a generator.
    • @@ -262,11 +262,11 @@ (10, 12, 14)

    #Type

      -
    • Everything is an object.
    • -
    • Every object has a type.
    • +
    • Everything in Python is an object.
    • +
    • Every object has a certain type.
    • Type and class are synonymous.
    • -
    <type> = type(<el>)                          # Or: <el>.__class__
    -<bool> = isinstance(<el>, <type>)            # Or: issubclass(type(<el>), <type>)
    +
    <type> = type(<el>)                # Returns object's type. Same as `<el>.__class__`.
    +<bool> = isinstance(<el>, <type>)  # Same result as `issubclass(type(<el>), <type>)`.
     
    @@ -294,50 +294,51 @@ >>> isinstance(123, Number) True
    -
    ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
    -┃                    │  Number  │  Complex │   Real   │ Rational │ Integral ┃
    -┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
    -┃ int                │    ✓     │    ✓     │    ✓     │    ✓     │    ✓     ┃
    -┃ fractions.Fraction │    ✓     │    ✓     │    ✓     │    ✓     │          ┃
    -┃ float              │    ✓     │    ✓     │    ✓     │          │          ┃
    -┃ complex            │    ✓     │    ✓     │          │          │          ┃
    -┃ decimal.Decimal    │    ✓     │          │          │          │          ┃
    -┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
    -
    -

    #String

    Immutable sequence of characters.

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    -<str>  = <str>.strip('<chars>')              # Strips passed characters. Also lstrip/rstrip().
    +
    ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
    +┃                    │   Number  │  Complex  │   Real   │ Rational │ Integral ┃
    +┠────────────────────┼───────────┼───────────┼──────────┼──────────┼──────────┨
    +┃ int                │     ✓     │     ✓     │    ✓     │    ✓     │    ✓     ┃
    +┃ fractions.Fraction │     ✓     │     ✓     │    ✓     │    ✓     │          ┃
    +┃ float              │     ✓     │     ✓     │    ✓     │          │          ┃
    +┃ complex            │     ✓     │     ✓     │          │          │          ┃
    +┃ decimal.Decimal    │     ✓     │           │          │          │          ┃
    +┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
    +
    +

    #String

    Immutable sequence of characters.

    <str>  = 'abc'                               # Also "abc". Interprets \n, \t, \x00-\xff, etc.
     
    -
    <list> = <str>.split()                       # Splits on one or more whitespace characters.
    +
    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    +<str>  = <str>.strip('<chars>')              # Strips passed characters. Also lstrip/rstrip().
    +
    +
    <list> = <str>.split()                       # Splits it on one or more whitespace characters.
     <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' string at most 'maxsplit' times.
     <list> = <str>.splitlines(keepends=False)    # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
    -<str>  = <str>.join(<coll_of_strings>)       # Joins elements by using string as a separator.
    +<str>  = <str>.join(<coll_of_strings>)       # Joins items by using the string as a separator.
     
    -
    <bool> = <sub_str> in <str>                  # Checks if string contains the substring.
    -<bool> = <str>.startswith(<sub_str>)         # Pass tuple of strings for multiple options.
    +
    <bool> = <sub_str> in <str>                  # Returns True if string contains the substring.
    +<bool> = <str>.startswith(<sub_str>)         # Pass tuple of strings to give multiple options.
     <int>  = <str>.find(<sub_str>)               # Returns start index of the first match or -1.
     
    <str>  = <str>.lower()                       # Lowers the case. Also upper/capitalize/title().
    -<str>  = <str>.casefold()                    # Same, but converts ẞ/ß to ss, Σ/ς to σ, etc.
    +<str>  = <str>.casefold()                    # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc.
     <str>  = <str>.replace(old, new [, count])   # Replaces 'old' with 'new' at most 'count' times.
    -<str>  = <str>.translate(<table>)            # Use `str.maketrans(<dict>)` to generate table.
    +<str>  = <str>.translate(table)              # Use `str.maketrans(<dict>)` to generate table.
     
    -
    <str>  = chr(<int>)                          # Converts passed integer to Unicode character.
    -<int>  = ord(<str>)                          # Converts passed Unicode character to integer.
    +
    <str>  = chr(<int>)                          # Converts passed integer into Unicode character.
    +<int>  = ord(<str>)                          # Converts passed Unicode character into integer.
     
    • Use 'unicodedata.normalize("NFC", <str>)' 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

    <bool> = <str>.isdecimal()                   # Checks for [0-9]. Also [०-९] and [٠-٩].
    -<bool> = <str>.isdigit()                     # Checks for [²³¹…] and isdecimal().
    -<bool> = <str>.isnumeric()                   # Checks for [¼½¾…], [零〇一…] and isdigit().
    -<bool> = <str>.isalnum()                     # Checks for [a-zA-Z…] and isnumeric().
    -<bool> = <str>.isprintable()                 # Checks for [ !#$%…] and isalnum().
    -<bool> = <str>.isspace()                     # Checks for [ \t\n\r\f\v\x1c-\x1f\x85…].
    -
    - +
    <bool> = <str>.isdecimal()                   # Checks all chars for [0-9]. Also [०-९], [٠-٩].
    +<bool> = <str>.isdigit()                     # Checks for [²³¹…] and isdecimal(). Also [፩-፱].
    +<bool> = <str>.isnumeric()                   # Checks for [¼½¾…] and isdigit(). Also [零〇一…].
    +<bool> = <str>.isalnum()                     # Checks for [ABC…] and isnumeric(). Also [ªµº…].
    +<bool> = <str>.isprintable()                 # Checks for [ !"#$…] and isalnum(). Also emojis.
    +<bool> = <str>.isspace()                     # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…].
    +

    #Regex

    Functions for regular expression matching.

    import re
     <str>   = re.sub(r'<regex>', new, text, count=0)  # Substitutes all occurrences with 'new'.
     <list>  = re.findall(r'<regex>', text)            # Returns all occurrences of the pattern.
    @@ -448,7 +449,7 @@
     
  • 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

    {90:c}                                   # 'Z'. Unicode character with value 90.
    +

    Ints

    {90:c}                                   # 'Z'. Returns Unicode character with value 90.
     {90:b}                                   # '1011010'. Binary representation of the int.
     {90:X}                                   # '5A'. Hexadecimal with upper-case letters.
     
    @@ -488,8 +489,8 @@

    Random

    from random import random, randint, uniform    # Also: gauss, choice, shuffle, seed.
     
    -
    <float> = random()                             # Returns a float inside [0, 1).
    -<num>   = randint/uniform(a, b)                # Returns an int/float inside [a, b].
    +
    <float> = random()                             # Select a random float from [0, 1).
    +<num>   = randint/uniform(a, b)                # Select an int/float from [a, b].
     <float> = gauss(mean, stdev)                   # Also triangular(low, high, mode).
     <el>    = choice(<sequence>)                   # Keeps it intact. Also sample(p, n).
     shuffle(<list>)                                # Works on all mutable sequences.
    @@ -664,7 +665,7 @@
     
     
    <iter> = map(lambda x: x + 1, range(10))            # Returns iter([1, 2, ..., 10]).
     <iter> = filter(lambda x: x > 5, range(10))         # Returns iter([6, 7, 8, 9]).
    -<obj>  = reduce(lambda out, x: out + x, range(10))  # Returns 45.
    +<obj>  = reduce(lambda out, x: out + x, range(10))  # Returns 45. Accepts 'initial'.
     

    Any, All

    <bool> = any(<collection>)                          # Is `bool(<el>)` True for any el?
     <bool> = all(<collection>)                          # True for all? Also True if empty.
    @@ -697,9 +698,9 @@
     player = Player(point, direction)                   # Returns its instance.
     
    -

    #Imports

    Mechanism that makes code in one file available to another file.

    import <module>            # Imports a built-in or '<module>.py'.
    -import <package>           # Imports a built-in or '<package>/__init__.py'.
    -import <package>.<module>  # Imports a built-in or '<package>/<module>.py'.
    +

    #Imports

    Mechanism that makes code in one file available to another file.

    import <module>                # Imports a built-in or '<module>.py'.
    +import <package>               # Imports a built-in or '<package>/__init__.py'.
    +import <package>.<module>      # Imports a built-in or '<package>/<module>.py'.
     
    @@ -805,7 +806,7 @@
      -
    • 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.
    • +
    • 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 how­ever manually check if the argument they received is a function and act accordingly.

    #Class

    A template for creating user-defined objects.

    class MyClass:
         def __init__(self, a):
    @@ -1232,7 +1233,7 @@
     func_name = <name>.__traceback__.tb_frame.f_code.co_name
     line_str  = linecache.getline(filename, <name>.__traceback__.tb_lineno)
     trace_str = ''.join(traceback.format_tb(<name>.__traceback__))
    -error_msg = ''.join(traceback.format_exception(type(<name>), <name>, <name>.__traceback__))
    +error_msg = ''.join(traceback.format_exception(*sys.exc_info()))
     

    Built-in Exceptions

    BaseException
    @@ -1242,16 +1243,16 @@
           ├── ArithmeticError         # Base class for arithmetic errors such as ZeroDivisionError.
           ├── AssertionError          # Raised by `assert <exp>` 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.
    +      ├── EOFError                # Is 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 index of a sequence (list/str) is out of range.
    -      │    └── KeyError           # Raised when a dictionary key or set element is missing.
    +      │    └── KeyError           # Raised when a dictionary key or a 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 and ConnectionAbortedError.
    -      ├── RuntimeError            # Raised by errors that don't fall into other categories.
    +      ├── RuntimeError            # Is raised by errors that don't fit into other categories.
           │    ├── 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 exhausted (empty) iterator is passed to next().
    @@ -1269,8 +1270,8 @@
     ┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
     
    -

    Useful built-in exceptions:

    raise TypeError('Argument is of the wrong type!')
    -raise ValueError('Argument has the right type but an inappropriate value!')
    +

    Useful built-in exceptions:

    raise TypeError('Passed argument is of the wrong type!')
    +raise ValueError('Argument has the right type but its value is off!')
     raise RuntimeError('I am too lazy to define my own exception!')
     
    @@ -1279,9 +1280,9 @@

    #Exit

    Exits the interpreter by raising SystemExit exception.

    import sys
    -sys.exit()                        # Exits with exit code 0 (success).
    -sys.exit(<int>)                   # Exits with the passed exit code.
    -sys.exit(<obj>)                   # Prints to stderr and exits with 1.
    +sys.exit()                     # Exits with exit code 0 (success).
    +sys.exit(<int>)                # Exits with the passed exit code.
    +sys.exit(<obj>)                # Prints to stderr and exits with 1.
     
    @@ -1319,7 +1320,7 @@ p.add_argument('-<short_name>', '--<name>', type=<type>) # Option (defaults to None). p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument. p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args. -p.add_argument('<name>', type=<type>, nargs='?/*') # Optional argument/s. +p.add_argument('<name>', type=<type>, nargs='?') # Optional argument. Also *. args = p.parse_args() # Exits on parsing error. <obj> = args.<name> # Returns `<type>(<arg>)`.
    @@ -1393,8 +1394,8 @@ <str> = os.path.join(<path>, ...) # Uses os.sep to join strings or Path objects. <str> = os.path.realpath(<path>) # Resolves symlinks and calls path.abspath().
    -
    <str>  = os.path.basename(<path>)   # Returns final component of the path.
    -<str>  = os.path.dirname(<path>)    # Returns path without the final component.
    +
    <str>  = os.path.basename(<path>)   # Returns path's final component, i.e. file/dir.
    +<str>  = os.path.dirname(<path>)    # Returns path with its final component removed.
     <tup.> = os.path.splitext(<path>)   # Splits on last period of the final component.
     
    <list> = os.listdir(path='.')       # Returns all filenames located at the path.
    @@ -1439,29 +1440,29 @@
     

    #OS Commands

    import os, shutil, subprocess
     
    -
    os.chdir(<path>)                    # Changes the current working directory (CWD).
    -os.mkdir(<path>, mode=0o777)        # Creates a directory. Permissions are in octal.
    -os.makedirs(<path>, mode=0o777)     # Creates all path's dirs. Also `exist_ok=False`.
    +
    os.chdir(<path>)                 # Changes the current working directory (CWD).
    +os.mkdir(<path>, mode=0o777)     # Creates a directory. Permissions are in octal.
    +os.makedirs(<path>, mode=0o777)  # Creates all path's dirs. Also `exist_ok=False`.
     
    -
    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.
    +
    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.
     
    -
    os.rename(from, to)                 # Renames or moves the file or directory 'from'.
    -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.
    +
    os.rename(from, to)              # Renames or moves the file or directory 'from'.
    +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.
     
    -
    os.remove(<path>)                   # Deletes the file. Or `pip3 install send2trash`.
    -os.rmdir(<path>)                    # Deletes the empty directory or raises OSError.
    -shutil.rmtree(<path>)               # Deletes the directory and all of its contents.
    +
    os.remove(<path>)                # Deletes the file. Or `pip3 install send2trash`.
    +os.rmdir(<path>)                 # Deletes the empty directory or raises OSError.
    +shutil.rmtree(<path>)            # Deletes the directory and all of its contents.
     
    • Paths can be either strings, Path objects, or DirEntry objects.
    • Functions report OS related errors by raising OSError or one of its subclasses.
    -

    Shell Commands

    <pipe> = os.popen('<commands>')     # Executes commands in sh/cmd. Returns combined stdout.
    -<str>  = <pipe>.read(size=-1)       # Reads 'size' chars or until EOF. Also readline/s().
    -<int>  = <pipe>.close()             # Returns None if last command exited with returncode 0.
    +

    Shell Commands

    <pipe> = os.popen('<commands>')  # Executes commands in sh/cmd. Returns combined stdout.
    +<str>  = <pipe>.read(size=-1)    # Reads 'size' chars or until EOF. Also readline/s().
    +<int>  = <pipe>.close()          # Returns None if last command exited with returncode 0.
     

    Sends "1 + 1" to the basic calculator and captures its output:

    >>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True)
    @@ -1477,8 +1478,8 @@
     

    #JSON

    Text file format for storing collections of strings and numbers.

    import json
    -<str>  = json.dumps(<list/dict>)    # Converts collection to JSON string.
    -<coll> = json.loads(<str>)          # Converts JSON string to collection.
    +<str>  = json.dumps(<list/dict>)  # Converts collection to JSON string.
    +<coll> = json.loads(<str>)        # Converts JSON string to collection.
     
    @@ -1493,8 +1494,8 @@

    #Pickle

    Binary file format for storing Python objects.

    import pickle
    -<bytes>  = pickle.dumps(<object>)   # Converts object to bytes object.
    -<object> = pickle.loads(<bytes>)    # Converts bytes object to object.
    +<bytes>  = pickle.dumps(<object>)  # Converts object to bytes object.
    +<object> = pickle.loads(<bytes>)   # Converts bytes object to object.
     
    @@ -1519,14 +1520,14 @@
    • Without the 'newline=""' argument, every '\r\n' sequence that is embedded inside a quoted field will get converted to '\n'! For details about newline argument see Open.
    • -
    • To print the spreadsheet to the console use Tabulate or PrettyTable library.
    • -
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • -
    • Reader accepts any iterator (or collection) of strings, not just files.
    • +
    • To print the spreadsheet to the console use either Tabulate or PrettyTable library.
    • +
    • For XML and binary Excel files (extensions xlsx, xlsm and xlsb) use Pandas library.
    • +
    • Reader accepts any iterator (or collection) of strings, not just text files.

    Write

    <file>   = open(<path>, 'w', newline='')  # Opens the CSV (text) file for writing.
     <writer> = csv.writer(<file>)             # Also: `dialect='excel', delimiter=','`.
     <writer>.writerow(<collection>)           # Encodes each object using `str(<el>)`.
    -<writer>.writerows(<coll_of_coll>)        # Appends multiple rows to the file.
    +<writer>.writerows(<coll_of_coll>)        # Appends multiple rows to opened file.
     
      @@ -1536,7 +1537,7 @@

      Parameters

      • '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'.
      • +
      • 'lineterminator' - Sets 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 instead of escaped.
      • @@ -1574,12 +1575,12 @@
    -

    Read

    <cursor> = <conn>.execute('<query>')           # Can raise a subclass of sqlite3.Error.
    +

    Read

    <cursor> = <conn>.execute('<query>')           # Can raise a subclass of the sqlite3.Error.
     <tuple>  = <cursor>.fetchone()                 # Returns the next row. Also next(<cursor>).
     <list>   = <cursor>.fetchall()                 # Returns remaining rows. Also list(<cursor>).
     
    -

    Write

    <conn>.execute('<query>')                      # Can raise a subclass of sqlite3.Error.
    +

    Write

    <conn>.execute('<query>')                      # Can raise a subclass of the sqlite3.Error.
     <conn>.commit()                                # Saves all changes since the last commit.
     <conn>.rollback()                              # Discards all changes since the last commit.
     
    @@ -1590,7 +1591,7 @@

    Placeholders

    <conn>.execute('<query>', <list/tuple>)        # Replaces every question mark with an item.
     <conn>.execute('<query>', <dict/namedtuple>)   # Replaces every :<key> with a matching value.
    -<conn>.executemany('<query>', <coll_of_coll>)  # Runs execute() once for each collection.
    +<conn>.executemany('<query>', <coll_of_coll>)  # Executes the query once for each collection.
     
      @@ -1610,7 +1611,7 @@ <engine> = create_engine('<url>') # Url: 'dialect://user:password@host/dbname'. <conn> = <engine>.connect() # Creates a connection. Also <conn>.close(). <cursor> = <conn>.execute(text('<query>'), …) # `<dict>`. Replaces every :<key> with value. -with <conn>.begin(): ... # Exits the block with commit or rollback. +with <conn>.begin(): ... # Exits the block with a commit or rollback.
    @@ -1623,10 +1624,10 @@ ┃ oracle+oracledb │ oracledb │ www.pypi.org/project/oracledb ┃ ┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
    -

    #Bytes

    A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
    +

    #Bytes

    A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

    <bytes> = b'<str>'                       # Only accepts ASCII chars and [\x00-\xff].
     <int>   = <bytes>[index]                 # Returns an integer in range from 0 to 255.
    -<bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
    -<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements by using bytes as a separator.
    +<bytes> = <bytes>[<slice>]               # Returns bytes even if it has one element.
    +<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes as a separator.
     
    @@ -1658,7 +1659,7 @@
    from struct import pack, unpack
     
     <bytes> = pack('<format>', <el_1> [, ...])  # Packs numbers according to format string.
    -<tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() to get iterator of tuples.
    +<tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() to get iter of tuples.
     
    @@ -1692,44 +1693,44 @@

    Format

    #Array

    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 (by calling the byteswap() method).

    from array import array
    +

    #Array

    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 sys­tem, however bytes of each element can be reversed (by calling the byteswap() method).

    from array import array
     
    -
    <array> = array('<typecode>', <coll_of_nums>)  # Creates an array from collection of numbers.
    -<array> = array('<typecode>', <bytes>)         # Writes passed bytes to the array's memory.
    -<array> = array('<typecode>', <array>)         # Treats passed array as a sequence of numbers.
    -<array>.fromfile(<file>, n_items)              # Appends file contents to the array's memory.
    +
    <array> = array('<typecode>' [, <coll>])  # Creates array. Accepts collection of numbers.
    +<array> = array('<typecode>', <bytes>)    # Copies passed bytes into the array's memory.
    +<array> = array('<typecode>', <array>)    # Treats passed array as a sequence of numbers.
    +<array>.fromfile(<file>, n_items)         # Appends file contents to the array's memory.
     
    -
    <bytes> = bytes(<array>)                       # Returns a copy of array's memory as bytes.
    -<file>.write(<array>)                          # Writes array's memory to the binary file.
    +
    <bytes> = bytes(<array>)                  # Returns a copy of array's memory as bytes.
    +<file>.write(<array>)                     # Appends array's memory to the binary file.
     
    -

    #Memory View

    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.

    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes is passed, else mutable.
    -<obj>   = <mview>[index]                       # Returns ints/floats. Bytes if format is 'c'.
    -<mview> = <mview>[<slice>]                     # Returns memoryview with rearranged elements.
    -<mview> = <mview>.cast('<typecode>')           # Only works between B/b/c and other types.
    -<mview>.release()                              # Releases memory buffer of the base object.
    +

    #Memory View

    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.

    <mview> = memoryview(<bytes/array>)       # Returns mutable memoryview if array is passed.
    +<obj>   = <mview>[index]                  # Returns an int/float. Bytes if format is 'c'.
    +<mview> = <mview>[<slice>]                # Returns memoryview with rearranged elements.
    +<mview> = <mview>.cast('<typecode>')      # Only works between B/b/c and the other types.
    +<mview>.release()                         # Releases the memory buffer of the base object.
     
    -
    <bytes> = bytes(<mview>)                       # Returns a new bytes object. Also bytearray().
    -<bytes> = <bytes>.join(<coll_of_mviews>)       # Joins memoryviews using bytes as a separator.
    -<array> = array('<typecode>', <mview>)         # Treats memoryview as a sequence of numbers.
    -<file>.write(<mview>)                          # Writes `bytes(<mview>)` to the binary file.
    +
    <bytes> = bytes(<mview>)                  # Returns a new bytes object. Also bytearray().
    +<bytes> = <bytes>.join(<coll_of_mviews>)  # Joins memoryviews using bytes as a separator.
    +<array> = array('<typecode>', <mview>)    # Treats passed mview as a sequence of numbers.
    +<file>.write(<mview>)                     # Appends `bytes(<mview>)` to the binary file.
     
    -
    <list>  = list(<mview>)                        # Returns a list of ints, floats or bytes.
    -<str>   = str(<mview>, 'utf-8')                # Treats passed memoryview as a bytes object.
    -<str>   = <mview>.hex()                        # Returns hex pairs. Accepts `sep=<str>`.
    +
    <list>  = list(<mview>)                   # Returns list of ints, floats or bytes objects.
    +<str>   = str(<mview>, 'utf-8')           # Treats passed memoryview as `bytes(<mview>)`.
    +<str>   = <mview>.hex()                   # Returns hexadecimal pairs. Also `sep=<str>`.
     

    #Deque

    List with efficient appends and pops from either side.

    from collections import deque
     
    -
    <deque> = deque(<collection>)                  # Use `maxlen=<int>` to set size limit.
    -<deque>.appendleft(<el>)                       # Opposite element is dropped if full.
    -<deque>.extendleft(<collection>)               # Prepends reversed coll. to the deque.
    -<deque>.rotate(n=1)                            # Last element becomes the first one.
    -<el> = <deque>.popleft()                       # Raises IndexError if deque is empty.
    +
    <deque> = deque(<collection>)     # Use `maxlen=<int>` to set size limit.
    +<deque>.appendleft(<el>)          # Opposite element is dropped if full.
    +<deque>.extendleft(<collection>)  # Prepends reversed coll. to the deque.
    +<deque>.rotate(n=1)               # Last element becomes the first one.
    +<el> = <deque>.popleft()          # Raises IndexError if deque is empty.
     

    #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 first, third and fifth line are also ordered by precedence within a group.

    import operator as op
     
    @@ -1751,7 +1752,7 @@

    Format

    'x < y < z' gets converted to '(x < y) and (y < z)'. +
  • Comparisons can be chained: 'x < y < z' gets converted to '(x < y) and (y < z)'.
  • #Match Statement

    Executes the first block with matching pattern.

    match <object/expression>:
         case <pattern> [if <condition>]:
    @@ -1760,15 +1761,15 @@ 

    Format

    Patterns

    <value_pattern> = 1/'abc'/True/None/math.pi        # Matches the literal or a dotted name.
    +

    Patterns

    <value_pattern> = 1/'abc'/True/None/math.pi        # Matches the literal or attribute's value.
     <class_pattern> = <type>()                         # Matches any object of that type (or ABC).
     <wildcard_patt> = _                                # Matches any object. Useful in last case.
     <capture_patt>  = <name>                           # Matches any object and binds it to name.
     <as_pattern>    = <pattern> as <name>              # Binds match to name. Also <type>(<name>).
     <or_pattern>    = <pattern> | <pattern> [| ...]    # Matches if any of listed patterns match.
     <sequence_patt> = [<pattern>, ...]                 # Matches a sequence. All items must match.
    -<mapping_patt>  = {<value_pattern>: <patt>, ...}   # Matches a dict that has matching items.
    -<class_pattern> = <type>(<attr_name>=<patt>, ...)  # Matches an object if attributes match.
    +<mapping_patt>  = {<value_pattern>: <patt>, ...}   # Matches a dict if it has matching items.
    +<class_pattern> = <type>(<attr_name>=<patt>, ...)  # Matches object that has matching attrbs.
     
      @@ -1797,19 +1798,19 @@

      Format

      # Error() that appends caught exception.

    Setup

    log.basicConfig(
    -    filename=None,                                # Logs to stderr or appends to file.
    +    filename=None,                                # Prints 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.
    +    level=log.WARNING,                            # Drops messages with a lower priority.
         handlers=[log.StreamHandler(sys.stderr)]      # Uses FileHandler if filename is set.
     )
     
    -
    <Formatter> = log.Formatter('<format>')           # Formats messages according to format str.
    +
    <Formatter> = log.Formatter('<format>')           # Formats messages according to format.
     <Handler> = log.FileHandler(<path>, mode='a')     # Appends to file. Also `encoding=None`.
     <Handler>.setFormatter(<Formatter>)               # Only outputs bare messages by default.
    -<Handler>.setLevel(<int/str>)                     # Prints or saves every message by default.
    +<Handler>.setLevel(<int/str>)                     # Prints/saves every message by default.
     <Logger>.addHandler(<Handler>)                    # Logger can have more than one handler.
    -<Logger>.setLevel(<int/str>)                      # What is sent to its/ancestors' handlers.
    +<Logger>.setLevel(<int/str>)                      # What's sent to its/ancestors' handlers.
     <Logger>.propagate = <bool>                       # Cuts off ancestors' handlers if False.
     
      @@ -1839,7 +1840,7 @@

      Format

      <list> = dir(<obj>) # Returns names of object's attributes (including methods). <dict> = vars(<obj>) # Returns dict of writable attributes. Also <obj>.__dict__. -<bool> = hasattr(<obj>, '<name>') # Checks if object possesses attribute with passed name. +<bool> = hasattr(<obj>, '<name>') # Checks if object possesses attribute of the passed name. value = getattr(<obj>, '<name>') # Returns the object's attribute or raises AttributeError. setattr(<obj>, '<name>', value) # Sets attribute. Only works on objects with __dict__ attr. delattr(<obj>, '<name>') # Deletes attribute from __dict__. Also `del <obj>.<name>`. @@ -1856,7 +1857,7 @@

      Format

      Thread

      <Thread> = Thread(target=<function>)           # Use `args=<collection>` to set the arguments.
       <Thread>.start()                               # Starts the thread. Also <Thread>.is_alive().
      -<Thread>.join()                                # Waits for the thread to finish executing.
      +<Thread>.join()                                # Waits until the thread has finished executing.
       
        @@ -1874,20 +1875,20 @@

        Format

        Semaphore, Event, Barrier

        <Semaphore> = Semaphore(value=1)               # Lock that can be acquired by 'value' threads.
         <Event>     = Event()                          # Method wait() blocks until set() is called.
        -<Barrier>   = Barrier(<int>)                   # Wait() blocks until it's called int times.
        +<Barrier>   = Barrier(<int>)                   # Wait() blocks until it's called integer times.
         

        Queue

        <Queue> = queue.Queue(maxsize=0)               # A first-in-first-out queue. It's thread safe.
        -<Queue>.put(<obj>)                             # Call blocks until queue stops being full.
        +<Queue>.put(<obj>)                             # The call blocks until queue stops being full.
         <Queue>.put_nowait(<obj>)                      # Raises queue.Full exception if queue is full.
        -<obj> = <Queue>.get()                          # Call blocks until queue stops being empty.
        -<obj> = <Queue>.get_nowait()                   # Raises queue.Empty exception if it's empty.
        +<obj> = <Queue>.get()                          # The call blocks until queue stops being empty.
        +<obj> = <Queue>.get_nowait()                   # Raises queue.Empty exception if it is empty.
         

        Thread Pool Executor

        <Exec> = ThreadPoolExecutor(max_workers=None)  # Also `with ThreadPoolExecutor() as <name>: …`.
         <iter> = <Exec>.map(<func>, <args_1>, ...)     # Multithreaded and non-lazy map(). Keeps order.
         <Futr> = <Exec>.submit(<func>, <arg_1>, ...)   # Creates a thread and returns its Future obj.
        -<Exec>.shutdown()                              # Waits for all threads to finish executing.
        +<Exec>.shutdown()                              # Waits for all the threads to finish executing.
         
        <bool> = <Future>.done()                       # Checks if the thread has finished executing.
        @@ -1902,7 +1903,7 @@ 

        Format

        #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 consume as much memory.
        • -
        • Coroutine definition starts with 'async' keyword and its call with 'await'.
        • +
        • Coroutine definition starts with 'async' keyword and its call with 'await' keyword.
        • Use 'asyncio.run(<coroutine>)' to start the first/main coroutine.
        import asyncio as aio
         
        @@ -1915,7 +1916,7 @@

        Format

        <coro> = aio.gather(<coro/task>, ...) # Schedules coros. Returns list of results on await. <coro> = aio.wait(<tasks>, return_when=…) # `'ALL/FIRST_COMPLETED'`. Returns (done, pending). -<iter> = aio.as_completed(<coros/tasks>) # Iter of coros that return next result on await. +<iter> = aio.as_completed(<coros/tasks>) # Iter of coros. Each returns next result on await.

        Runs a terminal game where you control an asterisk that must avoid numbers:

        import asyncio, collections, curses, curses.textpad, enum, random
         
        @@ -2438,7 +2439,7 @@ 

        Format

        #Pygame

        Opes a window and draws a square that can be moved with arrow keys:

        # $ pip3 install pygame
        +

        #Pygame

        Opens a window and draws a square that can be moved with arrow keys:

        # $ pip3 install pygame
         import pygame as pg
         
         pg.init()
        @@ -2888,11 +2889,11 @@ 

        Format

        def __init__(self, <type> <arg_name>): # Also `cdef __dealloc__(self):`. self.<attr_name> = <arg_name> # Also `... free(<array/pointer>)`.

        -

        Virtual Environments

        System for installing libraries directly into project's directory.

        $ python3 -m venv NAME      # Creates virtual environment in current directory.
        -$ source NAME/bin/activate  # Activates it. On Windows run `NAME\Scripts\activate`.
        -$ pip3 install LIBRARY      # Installs the library into active environment.
        -$ python3 FILE              # Runs the script in active environment. Also `./FILE`.
        -$ deactivate                # Deactivates the active virtual environment.
        +

        Virtual Environments

        System for installing libraries directly into project's directory.

        $ python3 -m venv NAME         # Creates virtual environment in current directory.
        +$ source NAME/bin/activate     # Activates it. On Windows run `NAME\Scripts\activate`.
        +$ pip3 install LIBRARY         # Installs the library into active environment.
        +$ python3 FILE                 # Runs the script in active environment. Also `./FILE`.
        +$ deactivate                   # Deactivates the active virtual environment.
         
        @@ -2933,7 +2934,7 @@

        Format