Python - Cheatsheet

Contents

    1. Collections:   List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
    2. Types:            Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
    3. Syntax:           Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception.
    4. System:          Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands.
    5. Data:               JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.
    6. Advanced:     Threading, Operator, Match_Stmt, Logging, Introspection, Coroutines.
    7. Libraries:        Progress_Bar, Plots, Tables, Curses, GUIs, Scraping, Web, Profiling.
    8. Multimedia:    NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly.

Main

1if __name__ == '__main__':      # Runs main() if file wasn't imported.
2    main()

List

1<el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
2<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
1<list>.append(<el>)             # Or: <list> += [<el>]
2<list>.extend(<collection>)     # Or: <list> += <collection>
1<list>.sort()                   # Sorts in ascending order.
2<list>.reverse()                # Reverses the list in-place.
3<list> = sorted(<collection>)   # Returns a new sorted list.
4<iter> = reversed(<list>)       # Returns reversed iterator.
1sum_of_elements  = sum(<collection>)
2elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
3sorted_by_second = sorted(<collection>, key=lambda el: el[1])
4sorted_by_both   = sorted(<collection>, key=lambda el: (el[1], el[0]))
5flatter_list     = list(itertools.chain.from_iterable(<list>))
6product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
7list_of_chars    = list(<str>)
  • For details about sorted(), min() and max() see sortable.
  • Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
1<int> = len(<list>)             # Returns number of items. Also works on other collections.
2<int> = <list>.count(<el>)      # Returns number of occurrences. Also `if <el> in <coll>: ...`.
3<int> = <list>.index(<el>)      # Returns index of the first occurrence or raises ValueError.
4<el>  = <list>.pop()            # Removes and returns item from the end or at index if passed.
5<list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
6<list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
7<list>.clear()                  # Removes all items. Also works on dictionary and set.

Dictionary

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

Counter

1>>> from collections import Counter
2>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
3>>> counter = Counter(colors)
4>>> counter['yellow'] += 1
5Counter({'blue': 3, 'red': 2, 'yellow': 1})
6>>> counter.most_common()[0]
7('blue', 3)

Set

1<set> = set()                                   # `{}` returns a dictionary.
1<set>.add(<el>)                                 # Or: <set> |= {<el>}
2<set>.update(<collection> [, ...])              # Or: <set> |= <set>
1<set>  = <set>.union(<coll.>)                   # Or: <set> | <set>
2<set>  = <set>.intersection(<coll.>)            # Or: <set> & <set>
3<set>  = <set>.difference(<coll.>)              # Or: <set> - <set>
4<set>  = <set>.symmetric_difference(<coll.>)    # Or: <set> ^ <set>
5<bool> = <set>.issubset(<coll.>)                # Or: <set> <= <set>
6<bool> = <set>.issuperset(<coll.>)              # Or: <set> >= <set>
1<el> = <set>.pop()                              # Raises KeyError if empty.
2<set>.remove(<el>)                              # Raises KeyError if missing.
3<set>.discard(<el>)                             # 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.
1<frozenset> = frozenset(<collection>)

Tuple

Tuple is an immutable and hashable list.

1<tuple> = ()                               # Empty tuple.
2<tuple> = (<el>,)                          # Or: <el>,
3<tuple> = (<el_1>, <el_2> [, ...])         # Or: <el_1>, <el_2> [, ...]

Named Tuple

Tuple's subclass with named elements.

 1>>> from collections import namedtuple
 2>>> Point = namedtuple('Point', 'x y')
 3>>> p = Point(1, y=2)
 4Point(x=1, y=2)
 5>>> p[0]
 61
 7>>> p.x
 81
 9>>> getattr(p, 'y')
102

Range

Immutable and hashable sequence of integers.

1<range> = range(stop)                      # range(to_exclusive)
2<range> = range(start, stop)               # range(from_inclusive, to_exclusive)
3<range> = range(start, stop, ±step)        # range(from_inclusive, to_exclusive, ±step_size)
1>>> [i for i in range(3)]
2[0, 1, 2]

Enumerate

1for i, el in enumerate(<collection> [, i_start]):
2    ...

Iterator

1<iter> = iter(<collection>)                # `iter(<iter>)` returns unmodified iterator.
2<iter> = iter(<function>, to_exclusive)    # A sequence of return values until 'to_exclusive'.
3<el>   = next(<iter> [, default])          # Raises StopIteration or returns 'default' on end.
4<list> = list(<iter>)                      # Returns a list of iterator's remaining elements.

Itertools

1import itertools as it
1<iter> = it.count(start=0, step=1)         # Returns updated value endlessly. Accepts floats.
2<iter> = it.repeat(<el> [, times])         # Returns element endlessly or 'times' times.
3<iter> = it.cycle(<collection>)            # Repeats the sequence endlessly.
1<iter> = it.chain(<coll>, <coll> [, ...])  # Empties collections in order (figuratively).
2<iter> = it.chain.from_iterable(<coll>)    # Empties collections inside a collection in order.
1<iter> = it.islice(<coll>, to_exclusive)   # Only returns first 'to_exclusive' elements.
2<iter> = it.islice(<coll>, from_inc, )    # `to_exclusive, +step_size`. Indices can be None.

Generator

  • Any function that contains a yield statement returns a generator.
  • Generators and iterators are interchangeable.
1def count(start, step):
2    while True:
3        yield start
4        start += step
1>>> counter = count(10, 2)
2>>> next(counter), next(counter), next(counter)
3(10, 12, 14)

Type

  • Everything is an object.
  • Every object has a type.
  • Type and class are synonymous.
1<type> = type(<el>)                          # Or: <el>.__class__
2<bool> = isinstance(<el>, <type>)            # Or: issubclass(type(<el>), <type>)
1>>> type('a'), 'a'.__class__, str
2(<class 'str'>, <class 'str'>, <class 'str'>)

Some types do not have built-in names, so they must be imported:

1from 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 iter(), contains() and len().

1>>> from collections.abc import Iterable, Collection, Sequence
2>>> isinstance([1, 2, 3], Iterable)
3True
1+------------------+------------+------------+------------+
2|                  |  Iterable  | Collection |  Sequence  |
3+------------------+------------+------------+------------+
4| list, range, str |    yes     |    yes     |    yes     |
5| dict, set        |    yes     |    yes     |            |
6| iter             |    yes     |            |            |
7+------------------+------------+------------+------------+
1>>> from numbers import Number, Complex, Real, Rational, Integral
2>>> isinstance(123, Number)
3True
1+--------------------+----------+----------+----------+----------+----------+
2|                    |  Number  |  Complex |   Real   | Rational | Integral |
3+--------------------+----------+----------+----------+----------+----------+
4| int                |   yes    |   yes    |   yes    |   yes    |   yes    |
5| fractions.Fraction |   yes    |   yes    |   yes    |   yes    |          |
6| float              |   yes    |   yes    |   yes    |          |          |
7| complex            |   yes    |   yes    |          |          |          |
8| decimal.Decimal    |   yes    |          |          |          |          |
9+--------------------+----------+----------+----------+----------+----------+

String

Immutable sequence of characters.

1<str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
2<str>  = <str>.strip('<chars>')              # Strips passed characters. Also lstrip/rstrip().
1<list> = <str>.split()                       # Splits on one or more whitespace characters.
2<list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
3<list> = <str>.splitlines(keepends=False)    # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
4<str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
1<bool> = <sub_str> in <str>                  # Checks if string contains the substring.
2<bool> = <str>.startswith(<sub_str>)         # Pass tuple of strings for multiple options.
3<int>  = <str>.find(<sub_str>)               # Returns start index of the first match or -1.
4<int>  = <str>.index(<sub_str>)              # Same, but raises ValueError if missing.
1<str>  = <str>.lower()                       # Changes the case. Also upper/capitalize/title().
2<str>  = <str>.replace(old, new [, count])   # Replaces 'old' with 'new' at most 'count' times.
3<str>  = <str>.translate(<table>)            # Use `str.maketrans(<dict>)` to generate table.
1<str>  = chr(<int>)                          # Converts int to Unicode character.
2<int>  = ord(<str>)                          # Converts Unicode character to int.
  • 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

1<bool> = <str>.isdecimal()                   # Checks for [0-9]. Also [०-९] and [٠-٩].
2<bool> = <str>.isdigit()                     # Checks for [²³¹…] and isdecimal().
3<bool> = <str>.isnumeric()                   # Checks for [¼½¾], [零〇一…] and isdigit().
4<bool> = <str>.isalnum()                     # Checks for [a-zA-Z…] and isnumeric().
5<bool> = <str>.isprintable()                 # Checks for [ !#$%…] and isalnum().
6<bool> = <str>.isspace()                     # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…].

Regex

Functions for regular expression matching.

1import re
2<str>   = re.sub(r'<regex>', new, text, count=0)  # Substitutes all occurrences with 'new'.
3<list>  = re.findall(r'<regex>', text)            # Returns all occurrences as strings.
4<list>  = re.split(r'<regex>', text, maxsplit=0)  # Add brackets around regex to keep matches.
5<Match> = re.search(r'<regex>', text)             # First occurrence of the pattern or None.
6<Match> = re.match(r'<regex>', text)              # Searches only at the beginning of the text.
7<iter>  = re.finditer(r'<regex>', text)           # Returns all occurrences as Match objects.
  • 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 '.' also accept the '\n'.
  • 're.compile(<regex>)' returns a Pattern object with methods sub(), findall(), …

Match Object

1<str>   = <Match>.group()                         # Returns the whole match. Also group(0).
2<str>   = <Match>.group(1)                        # Returns part inside the first brackets.
3<tuple> = <Match>.groups()                        # Returns all bracketed parts.
4<int>   = <Match>.start()                         # Returns start index of the match.
5<int>   = <Match>.end()                           # Returns exclusive end index of the match.

Special Sequences

1'\d' == '[0-9]'                                   # Also [०-९…]. Matches a decimal character.
2'\w' == '[a-zA-Z0-9_]'                            # Also [ª²³…]. Matches an alphanumeric or _.
3'\s' == '[ \t\n\r\f\v]'                           # Also [\x1c-\x1f…]. Matches a whitespace.
  • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
  • It restricts special sequence matches to '[\x00-\x7f]' (the first 128 characters) and also prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
  • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).

Format

1<str> = f'{<el_1>}, {<el_2>}'            # Curly brackets can also contain expressions.
2<str> = '{}, {}'.format(<el_1>, <el_2>)  # Or: '{0}, {a}'.format(<el_1>, a=<el_2>)
3<str> = '%s, %s' % (<el_1>, <el_2>)      # Redundant and inferior C-style formatting.

Example

1>>> Person = collections.namedtuple('Person', 'name height')
2>>> person = Person('Jean-Luc', 187)
3>>> f'{person.name} is {person.height / 100} meters tall.'
4'Jean-Luc is 1.87 meters tall.'

General Options

1{<el>:<10}                               # '<el>      '
2{<el>:^10}                               # '   <el>   '
3{<el>:>10}                               # '      <el>'
4{<el>:.<10}                              # '<el>......'
5{<el>:0}                                 # '<el>'
  • Objects are rendered using 'format(<el>, <options>)'.
  • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
  • 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() method.

Strings

1{'abcde':10}                             # 'abcde     '
2{'abcde':10.3}                           # 'abc       '
3{'abcde':.3}                             # 'abc'
4{'abcde'!r:10}                           # "'abcde'   "

Numbers

1{123456:10}                              # '    123456'
2{123456:10,}                             # '   123,456'
3{123456:10_}                             # '   123_456'
4{123456:+10}                             # '   +123456'
5{123456:=+10}                            # '+   123456'
6{123456: }                               # ' 123456'
7{-123456: }                              # '-123456'

Floats

1{1.23456:10.3}                           # '      1.23'
2{1.23456:10.3f}                          # '     1.235'
3{1.23456:10.3e}                          # ' 1.235e+00'
4{1.23456:10.3%}                          # '  123.456%'

Comparison of presentation types:

 1+--------------+----------------+----------------+----------------+----------------+
 2|              |    {<float>}   |   {<float>:f}  |   {<float>:e}  |   {<float>:%}  |
 3+--------------+----------------+----------------+----------------+----------------+
 4|  0.000056789 |   '5.6789e-05' |    '0.000057'  | '5.678900e-05' |    '0.005679%' |
 5|  0.00056789  |   '0.00056789' |    '0.000568'  | '5.678900e-04' |    '0.056789%' |
 6|  0.0056789   |   '0.0056789'  |    '0.005679'  | '5.678900e-03' |    '0.567890%' |
 7|  0.056789    |   '0.056789'   |    '0.056789'  | '5.678900e-02' |    '5.678900%' |
 8|  0.56789     |   '0.56789'    |    '0.567890'  | '5.678900e-01' |   '56.789000%' |
 9|  5.6789      |   '5.6789'     |    '5.678900'  | '5.678900e+00' |  '567.890000%' |
10| 56.789       |  '56.789'      |   '56.789000'  | '5.678900e+01' | '5678.900000%' |
11+--------------+----------------+----------------+----------------+----------------+
 1+--------------+----------------+----------------+----------------+----------------+
 2|              |  {<float>:.2}  |  {<float>:.2f} |  {<float>:.2e} |  {<float>:.2%} |
 3+--------------+----------------+----------------+----------------+----------------+
 4|  0.000056789 |    '5.7e-05'   |      '0.00'    |   '5.68e-05'   |      '0.01%'   |
 5|  0.00056789  |    '0.00057'   |      '0.00'    |   '5.68e-04'   |      '0.06%'   |
 6|  0.0056789   |    '0.0057'    |      '0.01'    |   '5.68e-03'   |      '0.57%'   |
 7|  0.056789    |    '0.057'     |      '0.06'    |   '5.68e-02'   |      '5.68%'   |
 8|  0.56789     |    '0.57'      |      '0.57'    |   '5.68e-01'   |     '56.79%'   |
 9|  5.6789      |    '5.7'       |      '5.68'    |   '5.68e+00'   |    '567.89%'   |
10| 56.789       |    '5.7e+01'   |     '56.79'    |   '5.68e+01'   |   '5678.90%'   |
11+--------------+----------------+----------------+----------------+----------------+
  • '{<float>:g}' is '{<float>:.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

1{90:c}                                   # 'Z'. Unicode character with value 90.
2{90:b}                                   # '1011010'. Number 90 in binary.
3{90:X}                                   # '5A'. Number 90 in uppercase hexadecimal.

Numbers

1<int>      = int(<float/str/bool>)                # Or: math.floor(<float>)
2<float>    = float(<int/str/bool>)                # Or: <int/float>e±<int>
3<complex>  = complex(real=0, imag=0)              # Or: <int/float> ± <int/float>j
4<Fraction> = fractions.Fraction(0, 1)             # Or: Fraction(numerator=0, denominator=1)
5<Decimal>  = decimal.Decimal(<str/int>)           # Or: Decimal((sign, digits, exponent))
  • 'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
  • Decimal numbers are stored exactly, unlike most floats where '1.1 + 2.2 != 3.3'.
  • Floats can be compared with: 'math.isclose(<float>, <float>)'.
  • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.

Basic Functions

1<num> = pow(<num>, <num>)                         # Or: <number> ** <number>
2<num> = abs(<num>)                                # <float> = abs(<complex>)
3<num> = round(<num> [, ±ndigits])                 # `round(126, -1) == 130`

Math

1from math import e, pi, inf, nan, isinf, isnan    # `<el> == nan` is always False.
2from math import sin, cos, tan, asin, acos, atan  # Also: degrees, radians.
3from math import log, log10, log2                 # Log can accept base as second arg.

Statistics

1from statistics import mean, median, variance     # Also: stdev, quantiles, groupby.

Random

1from random import random, randint, choice        # Also: shuffle, gauss, triangular, seed.
2<float> = random()                                # A float inside [0, 1).
3<int>   = randint(from_inc, to_inc)               # An int inside [from_inc, to_inc].
4<el>    = choice(<sequence>)                      # Keeps the sequence intact.

Bin, Hex

1<int> = ±0b<bin>                                  # Or: ±0x<hex>
2<int> = int('±<bin>', 2)                          # Or: int('±<hex>', 16)
3<int> = int('±0b<bin>', 0)                        # Or: int('±0x<hex>', 0)
4<str> = bin(<int>)                                # Returns '[-]0b<bin>'.

Bitwise Operators

1<int> = <int> & <int>                             # And (0b1100 & 0b1010 == 0b1000).
2<int> = <int> | <int>                             # Or  (0b1100 | 0b1010 == 0b1110).
3<int> = <int> ^ <int>                             # Xor (0b1100 ^ 0b1010 == 0b0110).
4<int> = <int> << n_bits                           # Left shift. Use >> for right.
5<int> = ~<int>                                    # Not. Also -<int> - 1.

Combinatorics

1import itertools as it
1>>> list(it.product([0, 1], repeat=3))
2[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
3 (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
1>>> list(it.product('abc', 'abc'))                    #   a  b  c
2[('a', 'a'), ('a', 'b'), ('a', 'c'),                  # a x  x  x
3 ('b', 'a'), ('b', 'b'), ('b', 'c'),                  # b x  x  x
4 ('c', 'a'), ('c', 'b'), ('c', 'c')]                  # c x  x  x
1>>> list(it.combinations('abc', 2))                   #   a  b  c
2[('a', 'b'), ('a', 'c'),                              # a .  x  x
3 ('b', 'c')]                                          # b .  .  x
1>>> list(it.combinations_with_replacement('abc', 2))  #   a  b  c
2[('a', 'a'), ('a', 'b'), ('a', 'c'),                  # a x  x  x
3 ('b', 'b'), ('b', 'c'),                              # b .  x  x
4 ('c', 'c')]                                          # c .  .  x
1>>> list(it.permutations('abc', 2))                   #   a  b  c
2[('a', 'b'), ('a', 'c'),                              # a .  x  x
3 ('b', 'a'), ('b', 'c'),                              # b x  .  x
4 ('c', 'a'), ('c', 'b')]                              # c x  x  .

Datetime

Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable.

1# $ pip3 install python-dateutil
2from datetime import date, time, datetime, timedelta, timezone
3from dateutil.tz import tzlocal, gettz
1<D>  = date(year, month, day)               # Only accepts valid dates from 1 to 9999 AD.
2<T>  = time(hour=0, minute=0, second=0)     # Also: `microsecond=0, tzinfo=None, fold=0`.
3<DT> = datetime(year, month, day, hour=0)   # Also: `minute=0, second=0, microsecond=0, …`.
4<TD> = timedelta(weeks=0, days=0, hours=0)  # Also: `minutes=0, seconds=0, microseconds=0`.
  • Aware <a> time and datetime objects have defined timezone, while naive <n> don't. 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.
  • Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
  • Use '<D/DT>.weekday()' to get the day of the week as an int, with Monday being 0.

Now

1<D/DTn> = D/DT.today()                      # Current local date or naive DT. Also DT.now().
2<DTa>   = DT.now(<tzinfo>)                  # Aware DT from current time in passed timezone.
  • To extract time use '<DTn>.time()', '<DTa>.time()' or '<DTa>.timetz()'.

Timezone

1<tzinfo> = timezone.utc                     # London without daylight saving time (DST).
2<tzinfo> = timezone(<timedelta>)            # Timezone with fixed offset from UTC.
3<tzinfo> = tzlocal()                        # Local tz with dynamic offset. Also gettz().
4<tzinfo> = gettz('<Continent>/<City>')      # 'Continent/City_Name' timezone or None.
5<DTa>    = <DT>.astimezone([<tzinfo>])      # Converts DT to the passed or local fixed zone.
6<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>)  # Changes object's timezone without conversion.
  • Timezones returned by gettz(), tzlocal(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the zone's base offset.
  • Standard library's zoneinfo.ZoneInfo() can be used instead of gettz() on Python 3.9 and later. It requires 'tzdata' package on Windows. It doesn't return local tz if arg. is omitted.

Encode

1<D/T/DT> = D/T/DT.fromisoformat(<str>)      # Object from ISO string. Raises ValueError.
2<DT>     = DT.strptime(<str>, '<format>')   # Datetime from str, according to format.
3<D/DTn>  = D/DT.fromordinal(<int>)          # D/DT from days since the Gregorian NYE 1.
4<DTn>    = DT.fromtimestamp(<float>)        # Local naive DT from seconds since the Epoch.
5<DTa>    = DT.fromtimestamp(<float>, <tz>)  # Aware datetime from seconds since the Epoch.
  • 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

1<str>    = <D/T/DT>.isoformat(sep='T')      # Also `timespec='auto/hours/minutes/seconds/…'`.
2<str>    = <D/T/DT>.strftime('<format>')    # Custom string representation of the object.
3<int>    = <D/DT>.toordinal()               # Days since Gregorian NYE 1, ignoring time and tz.
4<float>  = <DTn>.timestamp()                # Seconds since the Epoch, from local naive DT.
5<float>  = <DTa>.timestamp()                # Seconds since the Epoch, from aware datetime.

Format

1>>> dt = datetime.strptime('2025-08-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
2>>> dt.strftime("%dth of %B '%y (%a), %I:%M %p %Z")
3"14th of August '25 (Thu), 11:39 PM UTC+02:00"
  • '%z' accepts '±HH[:]MM' and returns '±HHMM' or empty string if datetime 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 datetime is naive.

Arithmetics

1<bool>   = <D/T/DTn> > <D/T/DTn>            # Ignores time jumps (fold attribute). Also ==.
2<bool>   = <DTa>     > <DTa>                # Ignores jumps if they share tz object. Broken ==.
3<TD>     = <D/DTn>   - <D/DTn>              # Ignores jumps. Convert to UTC for actual delta.
4<TD>     = <DTa>     - <DTa>                # Ignores jumps if they share tzinfo object.
5<D/DT>   = <D/DT>    ± <TD>                 # Returned datetime can fall into missing hour.
6<TD>     = <TD>      * <float>              # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>.
7<float>  = <TD>      / <TD>                 # How many hours/weeks/years are in TD. Also //.

Arguments

Inside Function Call

1func(<positional_args>)                           # func(0, 0)
2func(<keyword_args>)                              # func(x=0, y=0)
3func(<positional_args>, <keyword_args>)           # func(0, y=0)

Inside Function Definition

1def func(<nondefault_args>): ...                  # def func(x, y): ...
2def func(<default_args>): ...                     # def func(x=0, y=0): ...
3def func(<nondefault_args>, <default_args>): ...  # def func(x, y=0): ...
  • Default values are evaluated when function is first encountered in the scope.
  • Any mutation of a mutable default value will persist between invocations!

Splat Operator

Inside Function Call

Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.

1args   = (1, 2)
2kwargs = {'x': 3, 'y': 4, 'z': 5}
3func(*args, **kwargs)

Is the same as:

1func(1, 2, x=3, y=4, z=5)

Inside Function Definition

Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.

1def add(*a):
2    return sum(a)
1>>> add(1, 2, 3)
26
1def f(*args): ...               # f(1, 2, 3)
2def f(x, *args): ...            # f(1, 2, 3)
3def f(*args, z): ...            # f(1, 2, z=3)
1def f(**kwargs): ...            # f(x=1, y=2, z=3)
2def f(x, **kwargs): ...         # f(x=1, y=2, z=3) | f(1, y=2, z=3)
1def 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)
2def 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)
3def f(*args, y, **kwargs): ...  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
1def f(*, x, y, z): ...          # f(x=1, y=2, z=3)
2def f(x, *, y, z): ...          # f(x=1, y=2, z=3) | f(1, y=2, z=3)
3def f(x, y, *, z): ...          # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)

Other Uses

1<list>  = [*<coll.> [, ...]]    # Or: list(<collection>) [+ ...]
2<tuple> = (*<coll.>, [...])     # Or: tuple(<collection>) [+ ...]
3<set>   = {*<coll.> [, ...]}    # Or: set(<collection>) [| ...]
4<dict>  = {**<dict> [, ...]}    # Or: dict(<dict>) [| ...] (since 3.9)
1head, *body, tail = <coll.>     # Head or tail can be omitted.

Inline

Lambda

1<func> = lambda: <return_value>                     # A single statement function.
2<func> = lambda <arg_1>, <arg_2>: <return_value>    # Also allows default arguments.

Comprehensions

1<list> = [i+1 for i in range(10)]                   # Or: [1, 2, ..., 10]
2<iter> = (i for i in range(10) if i > 5)            # Or: iter([6, 7, 8, 9])
3<set>  = {i+5 for i in range(10)}                   # Or: {5, 6, ..., 14}
4<dict> = {i: i*2 for i in range(10)}                # Or: {0: 0, 1: 2, ..., 9: 18}
1>>> [l+r for l in 'abc' for r in 'abc']             # Inner loop is on the right side.
2['aa', 'ab', 'ac', ..., 'cc']

Map, Filter, Reduce

1from functools import reduce
1<iter> = map(lambda x: x + 1, range(10))            # Or: iter([1, 2, ..., 10])
2<iter> = filter(lambda x: x > 5, range(10))         # Or: iter([6, 7, 8, 9])
3<obj>  = reduce(lambda out, x: out + x, range(10))  # Or: 45

Any, All

1<bool> = any(<collection>)                          # Is `bool(<el>)` True for any el?
2<bool> = all(<collection>)                          # True for all? Also True if empty.

Conditional Expression

1<obj> = <exp> if <condition> else <exp>             # Only one expression is evaluated.
1>>> [a if a else 'zero' for a in (0, 1, 2, 3)]      # `any([0, '', [], None]) == False`
2['zero', 1, 2, 3]

Named Tuple, Enum, Dataclass

1from collections import namedtuple
2Point = namedtuple('Point', 'x y')                  # Creates a tuple's subclass.
3point = Point(0, 0)                                 # Returns its instance.
1from enum import Enum
2Direction = Enum('Direction', 'N E S W')            # Creates an enum.
3direction = Direction.N                             # Returns its member.
1from dataclasses import make_dataclass
2Player = make_dataclass('Player', ['loc', 'dir'])   # Creates a class.
3player = Player(point, direction)                   # Returns its instance.

Imports

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

1import <module>            # Imports a built-in or '<module>.py'.
2import <package>           # Imports a built-in or '<package>/__init__.py'.
3import <package>.<module>  # Imports a built-in or '<package>/<module>.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 <package>' does not automatically provide access to the package's modules unless they are explicitly imported in its init script.
  • Location of the file that is passed to python command serves as a root of all local imports.
  • For relative imports use 'from .[…][<pkg/module>[.…]] import <obj>'.

Closure

We have/get a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns the nested function.

1def get_multiplier(a):
2    def out(b):
3        return a * b
4    return out
1>>> multiply_by_3 = get_multiplier(3)
2>>> multiply_by_3(10)
330
  • Any value that is referenced from within multiple nested functions gets shared.

Partial

1from functools import partial
2<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
1>>> def multiply(a, b):
2...     return a * b
3>>> multiply_by_3 = partial(multiply, 3)
4>>> multiply_by_3(10)
530
  • 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(<func>)', 'iter(<func>, to_exc)' and dataclass's 'field(default_factory=<func>)'.

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'.

1def get_counter():
2    i = 0
3    def out():
4        nonlocal i
5        i += 1
6        return i
7    return out
1>>> counter = get_counter()
2>>> counter(), counter(), counter()
3(1, 2, 3)

Decorator

  • A decorator takes a function, adds some functionality and returns it.
  • It can be any callable, but is usually implemented as a function that returns a closure.
1@decorator_name
2def function_that_gets_passed_to_decorator():
3    ...

Debugger Example

Decorator that prints function's name every time the function is called.

 1from functools import wraps
 2
 3def debug(func):
 4    @wraps(func)
 5    def out(*args, **kwargs):
 6        print(func.__name__)
 7        return func(*args, **kwargs)
 8    return out
 9
10@debug
11def add(x, y):
12    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'.

LRU Cache

Decorator that caches function's return values. All function's arguments must be hashable.

1from functools import lru_cache
2
3@lru_cache(maxsize=None)
4def fib(n):
5    return n if n < 2 else fib(n-2) + fib(n-1)
  • Default size of the cache is 128 values. Passing 'maxsize=None' makes it unbounded.
  • CPython interpreter limits recursion depth to 1000 by default. To increase it use 'sys.setrecursionlimit(<depth>)'.

Parametrized Decorator

A decorator that accepts arguments and returns a normal decorator that accepts a function.

 1from functools import wraps
 2
 3def debug(print_result=False):
 4    def decorator(func):
 5        @wraps(func)
 6        def out(*args, **kwargs):
 7            result = func(*args, **kwargs)
 8            print(func.__name__, result if print_result else '')
 9            return result
10        return out
11    return decorator
12
13@debug(print_result=True)
14def add(x, y):
15    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.

 1class MyClass:
 2    def __init__(self, a):
 3        self.a = a
 4    def __str__(self):
 5        return str(self.a)
 6    def __repr__(self):
 7        class_name = self.__class__.__name__
 8        return f'{class_name}({self.a!r})'
 9
10    @classmethod
11    def get_class_name(cls):
12        return cls.__name__
  • Return value of str() should be readable and of repr() unambiguous.
  • If only repr() is defined, it will also be used for str().
  • Methods decorated with '@staticmethod' do not receive 'self' nor 'cls' as their first arg.
1>>> obj = MyClass(1)
2>>> obj.a, str(obj), repr(obj)
3(1, '1', 'MyClass(1)')

Expressions that call the str() method:

1print(<el>)
2f'{<el>}'
3logging.warning(<el>)
4csv.writer(<file>).writerow([<el>])
5raise Exception(<el>)

Expressions that call the repr() method:

1print/str/repr([<el>])
2print/str/repr({<el>: <el>})
3f'{<el>!r}'
4Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z(<el>))
5>>> <el>

Inheritance

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5class Employee(Person):
6    def __init__(self, name, staff_num):
7        super().__init__(name)
8        self.staff_num = staff_num

Multiple inheritance:

1class A: pass
2class B: pass
3class C(A, B): pass

MRO determines the order in which parent classes are traversed when searching for a method or an attribute:

1>>> C.mro()
2[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]

Type Annotations

  • They add type hints to variables, arguments and functions ('def f() -> <type>:').
  • Hints are used by type checkers like mypy, data validation libraries such as Pydantic and lately also by Cython compiler. However, they are not enforced by CPython interpreter.
1from collections import abc
2
3<name>: <type> [| ...] [= <obj>]                              # `|` since 3.10.
4<name>: list/set/abc.Iterable/abc.Sequence[<type>] [= <obj>]  # Since 3.9.
5<name>: dict/tuple[<type>, ...] [= <obj>]                     # Since 3.9.

Dataclass

Decorator that uses class variables to generate init(), repr() and eq() special methods.

1from dataclasses import dataclass, field, make_dataclass
2
3@dataclass(order=False, frozen=False)
4class <class_name>:
5    <attr_name>: <type>
6    <attr_name>: <type> = <default_value>
7    <attr_name>: list/dict/set = field(default_factory=list/dict/set)
  • 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 '<attr_name>: list = []' would make a list that is shared among all instances. Its 'default_factory' argument can be any callable.
  • For attributes of arbitrary type use 'typing.Any'.
1<class> = make_dataclass('<class_name>', <coll_of_attribute_names>)
2<class> = make_dataclass('<class_name>', <coll_of_tuples>)
3<tuple> = ('<attr_name>', <type> [, <default_value>])

Property

Pythonic way of implementing getters and setters.

1class Person:
2    @property
3    def name(self):
4        return ' '.join(self._name)
5
6    @name.setter
7    def name(self, value):
8        self._name = value.split()
1>>> person = Person()
2>>> person.name = '\t Guido  van Rossum \n'
3>>> person.name
4'Guido van Rossum'

Slots

Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.

1class MyClassWithSlots:
2    __slots__ = ['a']
3    def __init__(self):
4        self.a = 1

Copy

1from copy import copy, deepcopy
2<object> = copy/deepcopy(<object>)

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. False is returned if both return NotImplemented.
  • Ne() automatically works on any object that has eq() defined.
1class MyComparable:
2    def __init__(self, a):
3        self.a = a
4    def __eq__(self, other):
5        if isinstance(other, type(self)):
6            return self.a == other.a
7        return NotImplemented

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().
 1class MyHashable:
 2    def __init__(self, a):
 3        self._a = a
 4    @property
 5    def a(self):
 6        return self._a
 7    def __eq__(self, other):
 8        if isinstance(other, type(self)):
 9            return self.a == other.a
10        return NotImplemented
11    def __hash__(self):
12        return hash(self.a)

Sortable

  • With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods 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.
  • For proper alphabetical order pass 'key=locale.strxfrm' to sorted() after running 'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'.
 1from functools import total_ordering
 2
 3@total_ordering
 4class MySortable:
 5    def __init__(self, a):
 6        self.a = a
 7    def __eq__(self, other):
 8        if isinstance(other, type(self)):
 9            return self.a == other.a
10        return NotImplemented
11    def __lt__(self, other):
12        if isinstance(other, type(self)):
13            return self.a < other.a
14        return NotImplemented

Iterator

  • Any object that has methods next() and iter() is an iterator.
  • Next() should return next item or raise StopIteration exception.
  • Iter() should return 'self'.
1class Counter:
2    def __init__(self):
3        self.i = 0
4    def __next__(self):
5        self.i += 1
6        return self.i
7    def __iter__(self):
8        return self
1>>> counter = Counter()
2>>> next(counter), next(counter), next(counter)
3(1, 2, 3)

Python has many different iterator objects:

Callable

  • All functions and classes have a call() method, hence are callable.
  • When this cheatsheet uses '<function>' as an argument, it actually means '<callable>'.
1class Counter:
2    def __init__(self):
3        self.i = 0
4    def __call__(self):
5        self.i += 1
6        return self.i
1>>> counter = Counter()
2>>> counter(), counter(), counter()
3(1, 2, 3)

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.
  • Any exception that happens inside the with block is passed to the exit() method.
  • The exit() method can suppress the exception by returning a true value.
1class MyOpen:
2    def __init__(self, filename):
3        self.filename = filename
4    def __enter__(self):
5        self.file = open(self.filename)
6        return self.file
7    def __exit__(self, exc_type, exception, traceback):
8        self.file.close()
1>>> with open('test.txt', 'w') as file:
2...     file.write('Hello World!')
3>>> with MyOpen('test.txt') as file:
4...     print(file.read())
5Hello World!

Iterable Duck Types

Iterable

  • Only required method is iter(). It should return an iterator of object's items.
  • Contains() automatically works on any object that has iter() defined.
1class MyIterable:
2    def __init__(self, a):
3        self.a = a
4    def __iter__(self):
5        return iter(self.a)
6    def __contains__(self, el):
7        return el in self.a
1>>> obj = MyIterable([1, 2, 3])
2>>> [el for el in obj]
3[1, 2, 3]
4>>> 1 in obj
5True

Collection

  • Only required methods are iter() and len(). Len() should return the number of items.
  • This cheatsheet actually means '<iterable>' when it uses '<collection>'.
  • I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only 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.
1class MyCollection:
2    def __init__(self, a):
3        self.a = a
4    def __iter__(self):
5        return iter(self.a)
6    def __contains__(self, el):
7        return el in self.a
8    def __len__(self):
9        return len(self.a)

Sequence

  • 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 getitem() and len() defined.
 1class MySequence:
 2    def __init__(self, a):
 3        self.a = a
 4    def __iter__(self):
 5        return iter(self.a)
 6    def __contains__(self, el):
 7        return el in self.a
 8    def __len__(self):
 9        return len(self.a)
10    def __getitem__(self, i):
11        return self.a[i]
12    def __reversed__(self):
13        return reversed(self.a)

Discrepancies between glossary definitions and abstract base classes:

  • Glossary defines iterable as any object with iter() or getitem() and sequence as any object with getitem() and len(). It does not define collection.
  • Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has 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. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.
1from collections import abc
2
3class MyAbcSequence(abc.Sequence):
4    def __init__(self, a):
5        self.a = a
6    def __len__(self):
7        return len(self.a)
8    def __getitem__(self, i):
9        return self.a[i]

Table of required and automatically available special methods:

 1+------------+------------+------------+------------+--------------+
 2|            |  Iterable  | Collection |  Sequence  | abc.Sequence |
 3+------------+------------+------------+------------+--------------+
 4| iter()     |    REQ     |    REQ     |    Yes     |     Yes      |
 5| contains() |    Yes     |    Yes     |    Yes     |     Yes      |
 6| len()      |            |    REQ     |    REQ     |     REQ      |
 7| getitem()  |            |            |    REQ     |     REQ      |
 8| reversed() |            |            |    Yes     |     Yes      |
 9| index()    |            |            |            |     Yes      |
10| count()    |            |            |            |     Yes      |
11+------------+------------+------------+------------+--------------+
  • Method iter() is required for 'isinstance(<obj>, abc.Iterable)' to return True, however any object with getitem() will work with any code expecting an iterable.
  • Other extendable ABCs: MutableSequence, Set, MutableSet, Mapping, MutableMapping.
  • Names of their required methods are stored in '<abc>.__abstractmethods__'.

Enum

Class of named constants called members.

1from enum import Enum, auto
1class <enum_name>(Enum):
2    <member_name> = auto()              # Increment of the last numeric value or 1.
3    <member_name> = <value>             # Values don't have to be hashable.
4    <member_name> = <value>, <value>    # Tuple can be used for multiple values.
  • Methods receive the member they were called on as the 'self' argument.
  • Accessing a member named after a reserved keyword causes SyntaxError.
1<member> = <enum>.<member_name>         # Returns a member.
2<member> = <enum>['<member_name>']      # Returns a member. Raises KeyError.
3<member> = <enum>(<value>)              # Returns a member. Raises ValueError.
4<str>    = <member>.name                # Returns member's name.
5<obj>    = <member>.value               # Returns member's value.
1<list>   = list(<enum>)                 # Returns enum's members.
2<list>   = [a.name for a in <enum>]     # Returns enum's member names.
3<list>   = [a.value for a in <enum>]    # Returns enum's member values.
1<enum>   = type(<member>)               # Returns member's enum.
2<iter>   = itertools.cycle(<enum>)      # Returns endless iterator of members.
3<member> = random.choice(list(<enum>))  # Returns a random member.

Inline

1Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON')
2Cutlery = Enum('Cutlery', ['FORK', 'KNIFE', 'SPOON'])
3Cutlery = Enum('Cutlery', {'FORK': 1, 'KNIFE': 2, 'SPOON': 3})

User-defined functions cannot be values, so they must be wrapped:

1from functools import partial
2LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
3                           'OR':  partial(lambda l, r: l or r)})

Exceptions

1try:
2    <code>
3except <exception>:
4    <code>

Complex Example

 1try:
 2    <code_1>
 3except <exception_a>:
 4    <code_2_a>
 5except <exception_b>:
 6    <code_2_b>
 7else:
 8    <code_2_c>
 9finally:
10    <code_3>
  • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
  • 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, <func>)'.

Catching Exceptions

1except <exception>: ...
2except <exception> as <name>: ...
3except (<exception>, [...]): ...
4except (<exception>, [...]) as <name>: ...
  • Also catches subclasses of the exception.
  • Use 'traceback.print_exc()' to print the full error message to stderr.
  • Use 'print(<name>)' to print just the cause of the exception (its arguments).
  • Use 'logging.exception(<message>)' to log the passed message, followed by the full error message of the caught exception. For details see logging.
  • Use 'sys.exc_info()' to get exception type, object, and traceback of caught exception.

Raising Exceptions

1raise <exception>
2raise <exception>()
3raise <exception>(<el> [, ...])

Re-raising caught exception:

1except <exception> [as <name>]:
2    ...
3    raise

Exception Object

1arguments = <name>.args
2exc_type  = <name>.__class__
3filename  = <name>.__traceback__.tb_frame.f_code.co_filename
4func_name = <name>.__traceback__.tb_frame.f_code.co_name
5line      = linecache.getline(filename, <name>.__traceback__.tb_lineno)
6trace_str = ''.join(traceback.format_tb(<name>.__traceback__))
7error_msg = ''.join(traceback.format_exception(type(<name>), <name>, <name>.__traceback__))

Built-in Exceptions

 1BaseException
 2 +-- SystemExit                   # Raised by the sys.exit() function.
 3 +-- KeyboardInterrupt            # Raised when the user hits the interrupt key (ctrl-c).
 4 +-- Exception                    # User-defined exceptions should be derived from this class.
 5      +-- ArithmeticError         # Base class for arithmetic errors such as ZeroDivisionError.
 6      +-- AssertionError          # Raised by `assert <exp>` if expression returns false value.
 7      +-- AttributeError          # Raised when object doesn't have requested attribute/method.
 8      +-- EOFError                # Raised by input() when it hits an end-of-file condition.
 9      +-- LookupError             # Base class for errors when a collection can't find an item.
10      |    +-- IndexError         # Raised when a sequence index is out of range.
11      |    +-- KeyError           # Raised when a dictionary key or set element is missing.
12      +-- MemoryError             # Out of memory. May be too late to start deleting objects.
13      +-- NameError               # Raised when nonexistent name (variable/func/class) is used.
14      |    +-- UnboundLocalError  # Raised when local name is used before it's being defined.
15      +-- OSError                 # Errors such as FileExistsError/TimeoutError (see #Open).
16      |    +-- ConnectionError    # Errors such as BrokenPipeError/ConnectionAbortedError.
17      +-- RuntimeError            # Raised by errors that don't fall into other categories.
18      |    +-- NotImplementedEr…  # Can be raised by abstract methods or by unfinished code.
19      |    +-- RecursionError     # Raised when the maximum recursion depth is exceeded.
20      +-- StopIteration           # Raised when an empty iterator is passed to next().
21      +-- TypeError               # When an argument of the wrong type is passed to function.
22      +-- ValueError              # When argument has the right type but inappropriate value.

Collections and their exceptions:

1+-----------+------------+------------+------------+
2|           |    List    |    Set     |    Dict    |
3+-----------+------------+------------+------------+
4| getitem() | IndexError |            |  KeyError  |
5| pop()     | IndexError |  KeyError  |  KeyError  |
6| remove()  | ValueError |  KeyError  |            |
7| index()   | ValueError |            |            |
8+-----------+------------+------------+------------+

Useful built-in exceptions:

1raise TypeError('Argument is of the wrong type!')
2raise ValueError('Argument has the right type but an inappropriate value!')
3raise RuntimeError('I am too lazy to define my own exception!')

User-defined Exceptions

1class MyError(Exception): pass
2class MyInputError(MyError): pass

Exit

Exits the interpreter by raising SystemExit exception.

1import sys
2sys.exit()                        # Exits with exit code 0 (success).
3sys.exit(<el>)                    # Prints to stderr and exits with 1.
4sys.exit(<int>)                   # Exits with the passed exit code.

Print

1print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • Use 'file=sys.stderr' for messages about errors.
  • 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

1from pprint import pprint
2pprint(<collection>, width=80, depth=None, compact=False, sort_dicts=True)
  • Each item is printed on its own line if collection exceeds 'width' characters.
  • Nested collections that are 'depth' levels deep get printed as '...'.

Input

1<str> = input(prompt=None)
  • Reads a line from the user input or pipe if present (trailing newline gets stripped).
  • Prompt string is printed to the standard output before input is read.
  • Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.

Command Line Arguments

1import sys
2scripts_path = sys.argv[0]
3arguments    = sys.argv[1:]

Argument Parser

1from argparse import ArgumentParser, FileType
2p = ArgumentParser(description=<str>)                             # Returns a parser.
3p.add_argument('-<short_name>', '--<name>', action='store_true')  # Flag (defaults to False).
4p.add_argument('-<short_name>', '--<name>', type=<type>)          # Option (defaults to None).
5p.add_argument('<name>', type=<type>, nargs=1)                    # Mandatory first argument.
6p.add_argument('<name>', type=<type>, nargs='+')                  # Mandatory remaining args.
7p.add_argument('<name>', type=<type>, nargs='?/*')                # Optional argument/s.
8<args> = p.parse_args()                                           # Exits on parsing error.
9<obj>  = <args>.<name>                                            # Returns `<type>(<arg>)`.
  • Use 'help=<str>' to set argument description that will be displayed in help message.
  • Use 'default=<el>' to set option's or optional argument's default value.
  • Use 'type=FileType(<mode>)' for files. Accepts 'encoding', but 'newline' is None.

Open

Opens the file and returns a corresponding file object.

1<file> = open(<path>, 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 every '\n', '\r' and '\r\n'.

Modes

  • 'r' - Read (default).
  • 'w' - Write (truncate).
  • 'x' - Write or fail if the file already exists.
  • 'a' - Append.
  • 'w+' - Read and write (truncate).
  • 'r+' - Read and write from the start.
  • 'a+' - Read and write from the end.
  • 'b' - Binary mode ('br', 'bw', 'bx', …).

Exceptions

  • 'FileNotFoundError' can be raised when reading with 'r' or 'r+'.
  • 'FileExistsError' can be raised when writing with 'x'.
  • 'IsADirectoryError' and 'PermissionError' can be raised by any.
  • 'OSError' is the parent class of all listed exceptions.

File Object

1<file>.seek(0)                      # Moves to the start of the file.
2<file>.seek(offset)                 # Moves 'offset' chars/bytes from the start.
3<file>.seek(0, 2)                   # Moves to the end of the file.
4<bin_file>.seek(±offset, <anchor>)  # Anchor: 0 start, 1 current position, 2 end.
1<str/bytes> = <file>.read(size=-1)  # Reads 'size' chars/bytes or until EOF.
2<str/bytes> = <file>.readline()     # Returns a line or empty string/bytes on EOF.
3<list>      = <file>.readlines()    # Returns a list of remaining lines.
4<str/bytes> = next(<file>)          # Returns a line using buffer. Do not mix.
1<file>.write(<str/bytes>)           # Writes a string or bytes object.
2<file>.writelines(<collection>)     # Writes a coll. of strings or bytes objects.
3<file>.flush()                      # Flushes write buffer. Runs every 4096/8192 B.
4<file>.close()                      # Closes the file after flushing write buffer.
  • Methods do not add or strip trailing newlines, not even writelines().

Read Text from File

1def read_file(filename):
2    with open(filename, encoding='utf-8') as file:
3        return file.readlines()

Write Text to File

1def write_to_file(filename, text):
2    with open(filename, 'w', encoding='utf-8') as file:
3        file.write(text)

Paths

1import os, glob
2from pathlib import Path
1<str>  = os.getcwd()                # Returns current directory. Same as `$ pwd`.
2<str>  = os.path.join(<path>, ...)  # Joins two or more pathname components.
3<str>  = os.path.realpath(<path>)   # Resolves symlinks and calls path.abspath().
1<str>  = os.path.basename(<path>)   # Returns final component of the path.
2<str>  = os.path.dirname(<path>)    # Returns path without the final component.
3<tup.> = os.path.splitext(<path>)   # Splits on last period of the final component.
1<list> = os.listdir(path='.')       # Returns filenames located at the path.
2<list> = glob.glob('<pattern>')     # Returns paths matching the wildcard pattern.
1<bool> = os.path.exists(<path>)     # Or: <Path>.exists()
2<bool> = os.path.isfile(<path>)     # Or: <DirEntry/Path>.is_file()
3<bool> = os.path.isdir(<path>)      # Or: <DirEntry/Path>.is_dir()
1<stat> = os.stat(<path>)            # Or: <DirEntry/Path>.stat()
2<num>  = <stat>.st_mtime/st_size/  # Modification time, size in bytes, ...

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.

1<iter> = os.scandir(path='.')       # Returns DirEntry objects located at the path.
2<str>  = <DirEntry>.path            # Returns the whole path as a string.
3<str>  = <DirEntry>.name            # Returns final component as a string.
4<file> = open(<DirEntry>)           # Opens the file and returns a file object.

Path Object

1<Path> = Path(<path> [, ...])       # Accepts strings, Paths and DirEntry objects.
2<Path> = <path> / <path> [/ ...]    # First or second path must be a Path object.
3<Path> = <Path>.resolve()           # Returns absolute path with resolved symlinks.
1<Path> = Path()                     # Returns relative cwd. Also Path('.').
2<Path> = Path.cwd()                 # Returns absolute cwd. Also Path().resolve().
3<Path> = Path.home()                # Returns user's home directory (absolute).
4<Path> = Path(__file__).resolve()   # Returns script's path if cwd wasn't changed.
1<Path> = <Path>.parent              # Returns Path without the final component.
2<str>  = <Path>.name                # Returns final component as a string.
3<str>  = <Path>.stem                # Returns final component without extension.
4<str>  = <Path>.suffix              # Returns final component's extension.
5<tup.> = <Path>.parts               # Returns all components as strings.
1<iter> = <Path>.iterdir()           # Returns directory contents as Path objects.
2<iter> = <Path>.glob('<pattern>')   # Returns Paths matching the wildcard pattern.
1<str>  = str(<Path>)                # Returns path as a string.
2<file> = open(<Path>)               # Also <Path>.read/write_text/bytes().

OS Commands

1import os, shutil, subprocess
1os.chdir(<path>)                    # Changes the current working directory.
2os.mkdir(<path>, mode=0o777)        # Creates a directory. Permissions are in octal.
3os.makedirs(<path>, mode=0o777)     # Creates all path's dirs. Also `exist_ok=False`.
1shutil.copy(from, to)               # Copies the file. 'to' can exist or be a dir.
2shutil.copy2(from, to)              # Also copies creation and modification time.
3shutil.copytree(from, to)           # Copies the directory. 'to' must not exist.
1os.rename(from, to)                 # Renames/moves the file or directory.
2os.replace(from, to)                # Same, but overwrites file 'to' even on Windows.
3shutil.move(from, to)               # Rename() that moves into 'to' if it's a dir.
1os.remove(<path>)                   # Deletes the file.
2os.rmdir(<path>)                    # Deletes the empty directory.
3shutil.rmtree(<path>)               # Deletes the directory.
  • Paths can be either strings, Paths or DirEntry objects.
  • Functions report OS related errors by raising either OSError or one of its subclasses.

Shell Commands

1<pipe> = os.popen('<command>')      # Executes command in sh/cmd. Returns its stdout pipe.
2<str>  = <pipe>.read(size=-1)       # Reads 'size' chars or until EOF. Also readline/s().
3<int>  = <pipe>.close()             # Closes the pipe. Returns None on success (returncode 0).

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

1>>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True)
2CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')

Sends test.in to the basic calculator running in standard mode and saves its output to test.out:

1>>> from shlex import split
2>>> os.popen('echo 1 + 1 > test.in')
3>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
4CompletedProcess(args=['bc', '-s'], returncode=0)
5>>> open('test.out').read()
6'2\n'

JSON

Text file format for storing collections of strings and numbers.

1import json
2<str>    = json.dumps(<object>)     # Converts object to JSON string.
3<object> = json.loads(<str>)        # Converts JSON string to object.

Read Object from JSON File

1def read_json_file(filename):
2    with open(filename, encoding='utf-8') as file:
3        return json.load(file)

Write Object to JSON File

1def write_to_json_file(filename, an_object):
2    with open(filename, 'w', encoding='utf-8') as file:
3        json.dump(an_object, file, ensure_ascii=False, indent=2)

Pickle

Binary file format for storing Python objects.

1import pickle
2<bytes>  = pickle.dumps(<object>)   # Converts object to bytes object.
3<object> = pickle.loads(<bytes>)    # Converts bytes object to object.

Read Object from File

1def read_pickle_file(filename):
2    with open(filename, 'rb') as file:
3        return pickle.load(file)

Write Object to File

1def write_to_pickle_file(filename, an_object):
2    with open(filename, 'wb') as file:
3        pickle.dump(an_object, file)

CSV

Text file format for storing spreadsheets.

1import csv

Read

1<reader> = csv.reader(<file>)       # Also: `dialect='excel', delimiter=','`.
2<list>   = next(<reader>)           # Returns next row as a list of strings.
3<list>   = list(<reader>)           # 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!
  • To print the spreadsheet to the console use Tabulate library.
  • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
  • Reader accepts any iterator of strings, not just files.

Write

1<writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
2<writer>.writerow(<collection>)     # Encodes objects using `str(<el>)`.
3<writer>.writerows(<coll_of_coll>)  # 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="w"' to overwrite it or 'mode="a"' to append to it.

Parameters

  • 'dialect' - Master parameter that sets the default values. String or a 'csv.Dialect' object.
  • 'delimiter' - A one-character string used to separate fields.
  • 'lineterminator' - How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.
  • 'quotechar' - Character for quoting fields that contain special characters.
  • 'escapechar' - Character for escaping quotechars.
  • '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

 1+------------------+--------------+--------------+--------------+
 2|                  |     excel    |   excel-tab  |     unix     |
 3+------------------+--------------+--------------+--------------+
 4| delimiter        |       ','    |      '\t'    |       ','    |
 5| lineterminator   |    '\r\n'    |    '\r\n'    |      '\n'    |
 6| quotechar        |       '"'    |       '"'    |       '"'    |
 7| escapechar       |      None    |      None    |      None    |
 8| doublequote      |      True    |      True    |      True    |
 9| quoting          |         0    |         0    |         1    |
10| skipinitialspace |     False    |     False    |     False    |
11+------------------+--------------+--------------+--------------+

Read Rows from CSV File

1def read_csv_file(filename, dialect='excel', **params):
2    with open(filename, encoding='utf-8', newline='') as file:
3        return list(csv.reader(file, dialect, **params))

Write Rows to CSV File

1def write_to_csv_file(filename, rows, mode='w', dialect='excel', **params):
2    with open(filename, mode, encoding='utf-8', newline='') as file:
3        writer = csv.writer(file, dialect, **params)
4        writer.writerows(rows)

SQLite

A server-less database engine that stores each database into a separate file.

1import sqlite3
2<conn> = sqlite3.connect(<path>)                # Opens existing or new file. Also ':memory:'.
3<conn>.close()                                  # Closes the connection.

Read

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

Write

1<conn>.execute('<query>')                       # Can raise a subclass of sqlite3.Error.
2<conn>.commit()                                 # Saves all changes since the last commit.
3<conn>.rollback()                               # Discards all changes since the last commit.

Or:

1with <conn>:                                    # Exits the block with commit() or rollback(),
2    <conn>.execute('<query>')                   # depending on whether any exception occurred.

Placeholders

1<conn>.execute('<query>', <list/tuple>)         # Replaces '?'s in query with values.
2<conn>.execute('<query>', <dict/namedtuple>)    # Replaces ':<key>'s with values.
3<conn>.executemany('<query>', <coll_of_above>)  # Runs execute() multiple times.
  • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
  • Bools will be stored and returned as ints and dates as ISO formatted strings.

Example

Values are not actually saved in this example because 'conn.commit()' is omitted!

1>>> conn = sqlite3.connect('test.db')
2>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
3>>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
41
5>>> conn.execute('SELECT * FROM person').fetchall()
6[(1, 'Jean-Luc', 187)]

SqlAlchemy

1# $ pip3 install sqlalchemy
2from sqlalchemy import create_engine, text
3<engine> = create_engine('<url>')               # Url: 'dialect://user:password@host/dbname'.
4<conn>   = <engine>.connect()                   # Creates a connection. Also <conn>.close().
5<cursor> = <conn>.execute(text('<query>'), )   # Replaces ':<key>'s with keyword arguments.
6with <conn>.begin(): ...                        # Exits the block with commit or rollback.
1+------------+--------------+----------+----------------------------------+
2| Dialect    | pip3 install | import   |           Dependencies           |
3+------------+--------------+----------+----------------------------------+
4| mysql      | mysqlclient  | MySQLdb  | www.pypi.org/project/mysqlclient |
5| postgresql | psycopg2     | psycopg2 | www.pypi.org/project/psycopg2    |
6| mssql      | pyodbc       | pyodbc   | www.pypi.org/project/pyodbc      |
7| oracle     | oracledb     | oracledb | www.pypi.org/project/oracledb    |
8+------------+--------------+----------+----------------------------------+

Bytes

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

1<bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
2<int>   = <bytes>[index]                 # Returns an int in range from 0 to 255.
3<bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
4<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes as a separator.

Encode

1<bytes> = bytes(<coll_of_ints>)          # Ints must be in range from 0 to 255.
2<bytes> = bytes(<str>, 'utf-8')          # Encodes string. Also <str>.encode('utf-8').
3<bytes> = bytes.fromhex('<hex>')         # Hex pairs can be separated by whitespaces.
4<bytes> = <int>.to_bytes(n_bytes, )     # `byteorder='big/little', signed=False`.

Decode

1<list>  = list(<bytes>)                  # Returns ints in range from 0 to 255.
2<str>   = str(<bytes>, 'utf-8')          # Decodes bytes. Also <bytes>.decode('utf-8').
3<str>   = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
4<int>   = int.from_bytes(<bytes>, )     # `byteorder='big/little', signed=False`.

Read Bytes from File

1def read_bytes(filename):
2    with open(filename, 'rb') as file:
3        return file.read()

Write Bytes to File

1def write_bytes(filename, bytes_obj):
2    with open(filename, 'wb') as file:
3        file.write(bytes_obj)

Struct

  • Module that performs conversions between a sequence of numbers and a bytes object.
  • System’s type sizes, byte order, and alignment rules are used by default.
1from struct import pack, unpack
2
3<bytes> = pack('<format>', <el_1> [, ...])  # Packs objects according to format string.
4<tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() to get iterator of tuples.
1>>> pack('>hhl', 1, 2, 3)
2b'\x00\x01\x00\x02\x00\x00\x00\x03'
3>>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
4(1, 2, 3)

Format

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'.
  • '<n>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:

  • 'b' - char (1/1)
  • 'h' - short (2/2)
  • 'i' - int (2/4)
  • 'l' - long (4/4)
  • 'q' - long long (8/8)

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. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.

1from array import array
1<array> = array('<typecode>', <coll_of_nums>)  # Array from collection of numbers.
2<array> = array('<typecode>', <bytes>)         # Array from bytes object.
3<array> = array('<typecode>', <array>)         # Treats array as a sequence of numbers.
4<array>.fromfile(<file>, n_items)              # Appends items from the binary file.
1<bytes> = bytes(<array>)                       # Returns a copy of array's memory.
2<file>.write(<array>)                          # Writes array 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.

1<mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
2<real>  = <mview>[index]                       # Returns an int or a float.
3<mview> = <mview>[<slice>]                     # Returns mview with rearranged elements.
4<mview> = <mview>.cast('<typecode>')           # Only works between b/B/c and other types.
5<mview>.release()                              # Releases memory buffer of the base object.
1<bytes> = bytes(<mview>)                       # Returns a new bytes object.
2<bytes> = <bytes>.join(<coll_of_mviews>)       # Joins mviews using bytes as a separator.
3<array> = array('<typecode>', <mview>)         # Treats mview as a sequence of numbers.
4<file>.write(<mview>)                          # Writes mview to the binary file.
1<list>  = list(<mview>)                        # Returns a list of ints or floats.
2<str>   = str(<mview>, 'utf-8')                # Treats mview as a bytes object.
3<str>   = <mview>.hex()                        # Returns hex pairs. Accepts `sep=<str>`.

Deque

A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

1from collections import deque
1<deque> = deque(<collection>)                  # Use `maxlen=<int>` to set size limit.
2<deque>.appendleft(<el>)                       # Opposite element is dropped if full.
3<deque>.extendleft(<collection>)               # Passed collection gets reversed.
4<deque>.rotate(n=1)                            # Last element becomes first.
5<el> = <deque>.popleft()                       # Raises IndexError if deque is empty.

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.

1from threading import Thread, RLock, Semaphore, Event, Barrier
2from concurrent.futures import ThreadPoolExecutor, as_completed

Thread

1<Thread> = Thread(target=<function>)           # Use `args=<collection>` to set the arguments.
2<Thread>.start()                               # Starts the thread.
3<bool> = <Thread>.is_alive()                   # Checks if the thread has finished executing.
4<Thread>.join()                                # Waits for the thread to finish.
  • Use 'kwargs=<dict>' 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

1<lock> = RLock()                               # Lock that can only be released by acquirer.
2<lock>.acquire()                               # Waits for the lock to be available.
3<lock>.release()                               # Makes the lock available again.

Or:

1with <lock>:                                   # Enters the block by calling acquire() and
2    ...                                        # exits it with release(), even on error.

Semaphore, Event, Barrier

1<Semaphore> = Semaphore(value=1)               # Lock that can be acquired by 'value' threads.
2<Event>     = Event()                          # Method wait() blocks until set() is called.
3<Barrier>   = Barrier(n_times)                 # Wait() blocks until it's called n_times.

Queue

1<Queue> = queue.Queue(maxsize=0)               # A thread-safe first-in-first-out queue.
2<Queue>.put(<el>)                              # Blocks until queue stops being full.
3<Queue>.put_nowait(<el>)                       # Raises queue.Full exception if full.
4<el> = <Queue>.get()                           # Blocks until queue stops being empty.
5<el> = <Queue>.get_nowait()                    # Raises queue.Empty exception if empty.

Thread Pool Executor

1<Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: ...`
2<iter> = <Exec>.map(<func>, <args_1>, ...)     # Multithreaded and non-lazy map(). Keeps order.
3<Futr> = <Exec>.submit(<func>, <arg_1>, ...)   # Creates a thread and returns its Future obj.
4<Exec>.shutdown()                              # Blocks until all threads finish executing.
1<bool> = <Future>.done()                       # Checks if the thread has finished executing.
2<obj>  = <Future>.result(timeout=None)         # Waits for thread to finish and returns result.
3<bool> = <Future>.cancel()                     # Cancels or returns False if running/finished.
4<iter> = as_completed(<coll_of_Futures>)       # Next() waits for 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 thread finished on time.
  • Exceptions that happen inside threads are raised when next() is called on map's iterator or when result() is called on a Future. Its exception() method returns exception or None.
  • ProcessPoolExecutor provides true parallelism, but everything sent to/from workers must be pickable. Queues must be sent using executor's 'initargs' and 'initializer' parameters.

Operator

Module of functions that provide the functionality of operators. Functions are ordered by operator precedence, starting with least binding.

1import operator as op
2<bool> = op.not_(<obj>)                                         # or, and, not (or/and missing)
3<bool> = op.eq/ne/lt/le/gt/ge/is_/contains(<obj>, <obj>)        # ==, !=, <, <=, >, >=, is, in
4<obj>  = op.or_/xor/and_(<int/set>, <int/set>)                  # |, ^, &
5<int>  = op.lshift/rshift(<int>, <int>)                         # <<, >>
6<obj>  = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>)      # +, -, *, /, //, %
7<num>  = op.neg/invert(<num>)                                   # -, ~
8<num>  = op.pow(<num>, <num>)                                   # **
9<func> = op.itemgetter/attrgetter/methodcaller(<obj> [, ...])   # [index/key], .name, .name()
1elementwise_sum  = map(op.add, list_a, list_b)
2sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
3sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
4product_of_elems = functools.reduce(op.mul, <collection>)
5first_element    = op.methodcaller('pop', 0)(<list>)
  • Bitwise operators require objects to have or(), xor(), and(), lshift(), rshift() and invert() special methods, unlike logical operators that work on all types of objects.
  • Also: '<bool> = <bool> &|^ <bool>' and '<int> = <bool> &|^ <int>'.

Match Statement

Executes the first block with matching pattern. Added in Python 3.10.

1match <object/expression>:
2    case <pattern> [if <condition>]:
3        <code>
4    ...

Patterns

1<value_pattern> = 1/'abc'/True/None/math.pi          # Matches the literal or a dotted name.
2<class_pattern> = <type>()                           # Matches any object of that type.
3<wildcard_patt> = _                                  # Matches any object.
4<capture_patt>  = <name>                             # Matches any object and binds it to name.
5<or_pattern>    = <pattern> | <pattern> [| ...]      # Matches any of the patterns.
6<as_pattern>    = <pattern> as <name>                # Binds the match to the name.
7<sequence_patt> = [<pattern>, ...]                   # Matches sequence with matching items.
8<mapping_patt>  = {<value_pattern>: <pattern>, ...}  # Matches dictionary with matching items.
9<class_pattern> = <type>(<attr_name>=<patt>, ...)    # Matches object with matching attributes.
  • Sequence pattern can also be written as a tuple.
  • Use '*<name>' and '**<name>' in sequence/mapping patterns to bind remaining items.
  • Sequence pattern must match all items, 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.

Example

1>>> from pathlib import Path
2>>> match Path('/home/gto/python-cheatsheet/README.md'):
3...     case Path(
4...         parts=['/', 'home', user, *_],
5...         stem=stem,
6...         suffix=('.md' | '.txt') as suffix
7...     ) if stem.lower() == 'readme':
8...         print(f'{stem}{suffix} is a readme file that belongs to user {user}.')
9'README.md is a readme file that belongs to user gto.'

Logging

1import logging
1logging.basicConfig(filename=<path>, level='DEBUG')  # Configures the root logger (see Setup).
2logging.debug/info/warning/error/critical(<str>)     # Logs to the root logger.
3<Logger> = logging.getLogger(__name__)               # Logger named after the module.
4<Logger>.<level>(<str>)                              # Logs to the logger.
5<Logger>.exception(<str>)                            # Error() that appends caught exception.

Setup

1logging.basicConfig(
2    filename=None,                                   # Logs to console (stderr) by default.
3    format='%(levelname)s:%(name)s:%(message)s',     # Add '%(asctime)s' for local datetime.
4    level=logging.WARNING,                           # Drops messages with lower priority.
5    handlers=[logging.StreamHandler(sys.stderr)]     # Uses FileHandler if filename is set.
6)
1<Formatter> = logging.Formatter('<format>')          # Creates a Formatter.
2<Handler> = logging.FileHandler(<path>, mode='a')    # Creates a Handler. Also `encoding=None`.
3<Handler>.setFormatter(<Formatter>)                  # Adds Formatter to the Handler.
4<Handler>.setLevel(<int/str>)                        # Processes all messages by default.
5<Logger>.addHandler(<Handler>)                       # Adds Handler to the Logger.
6<Logger>.setLevel(<int/str>)                         # What is sent to its/ancestors' handlers.
7<Logger>.propagate = <bool>                          # Cuts off ancestors' handlers if False.
  • Parent logger can be specified by naming the child logger '<parent>.<name>'.
  • 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.
  • A 'handlers.RotatingFileHandler' creates and deletes log files based on 'maxBytes' and 'backupCount' arguments.

Creates a logger that writes all messages to file and sends them to the root's handler that prints warnings or higher:

 1>>> logger = logging.getLogger('my_module')
 2>>> handler = logging.FileHandler('test.log', encoding='utf-8')
 3>>> handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:%(name)s:%(message)s'))
 4>>> logger.addHandler(handler)
 5>>> logger.setLevel('DEBUG')
 6>>> logging.basicConfig()
 7>>> logging.root.handlers[0].setLevel('WARNING')
 8>>> logger.critical('Running out of disk space.')
 9CRITICAL:my_module:Running out of disk space.
10>>> print(open('test.log').read())
112023-02-07 23:21:01,430 CRITICAL:my_module:Running out of disk space.

Introspection

1<list> = dir()                             # Names of local variables, functions, classes, etc.
2<dict> = vars()                            # Dict of local variables, etc. Also locals().
3<dict> = globals()                         # Dict of global vars, etc. (incl. '__builtins__').
1<list> = dir(<object>)                     # Names of object's attributes (including methods).
2<dict> = vars(<object>)                    # Dict of writable attributes. Also <obj>.__dict__.
3<bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an AttributeError.
4value  = getattr(<object>, '<attr_name>')  # Default value can be passed as the third argument.
5setattr(<object>, '<attr_name>', value)    # Only works on objects with __dict__ attribute.
6delattr(<object>, '<attr_name>')           # Same. Also `del <object>.<attr_name>`.
1<Sig>  = inspect.signature(<function>)     # Returns function's Signature object.
2<dict> = <Sig>.parameters                  # Dict of Parameter objects. Also <Sig>.return_type.
3<memb> = <Param>.kind                      # Member of ParameterKind enum (KEYWORD_ONLY, ...).
4<obj>  = <Param>.default                   # Returns param's default value or Parameter.empty.
5<type> = <Param>.annotation                # Returns param's type hint or Parameter.empty.

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(<coroutine>)' is the main entry point for asynchronous programs.
1import asyncio as aio
1<coro> = <async_function>(<args>)         # Creates a coroutine by calling async def function.
2<obj>  = await <coroutine>                # Starts the coroutine and returns result.
3<task> = aio.create_task(<coroutine>)     # Schedules the coroutine for execution.
4<obj>  = await <task>                     # Returns result. Also <task>.cancel().
1<coro> = aio.gather(<coro/task>, ...)     # Schedules coroutines. Returns results when awaited.
2<coro> = aio.wait(<tasks>, )             # `aio.ALL/FIRST_COMPLETED`. Returns (done, pending).
3<iter> = aio.as_completed(<coros/tasks>)  # Iter of coros. All return next result when awaited.

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

 1import asyncio, collections, curses, curses.textpad, enum, random, time
 2
 3P = collections.namedtuple('P', 'x y')    # Position
 4D = enum.Enum('D', 'n e s w')             # Direction
 5W, H = 15, 7                              # Width, Height
 6
 7def main(screen):
 8    curses.curs_set(0)                    # Makes cursor invisible.
 9    screen.nodelay(True)                  # Makes getch() non-blocking.
10    asyncio.run(main_coroutine(screen))   # Starts running asyncio code.
11
12async def main_coroutine(screen):
13    moves = asyncio.Queue()
14    state = {'*': P(0, 0), **{id_: P(W//2, H//2) for id_ in range(10)}}
15    ai    = [random_controller(id_, moves) for id_ in range(10)]
16    mvc   = [human_controller(screen, moves), model(moves, state), view(state, screen)]
17    tasks = [asyncio.create_task(cor) for cor in ai + mvc]
18    await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
19
20async def random_controller(id_, moves):
21    while True:
22        d = random.choice(list(D))
23        moves.put_nowait((id_, d))
24        await asyncio.sleep(random.triangular(0.01, 0.65))
25
26async def human_controller(screen, moves):
27    while True:
28        key_mappings = {258: D.s, 259: D.n, 260: D.w, 261: D.e}
29        if d := key_mappings.get(screen.getch()):
30            moves.put_nowait(('*', d))
31        await asyncio.sleep(0.005)
32
33async def model(moves, state):
34    while state['*'] not in (state[id_] for id_ in range(10)):
35        id_, d = await moves.get()
36        deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
37        state[id_] = P((state[id_].x + deltas[d].x) % W, (state[id_].y + deltas[d].y) % H)
38
39async def view(state, screen):
40    offset = P(curses.COLS//2 - W//2, curses.LINES//2 - H//2)
41    while True:
42        screen.erase()
43        curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W)
44        for id_, p in state.items():
45            screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H,
46                          offset.x + (p.x - state['*'].x + W//2) % W, str(id_))
47        screen.refresh()
48        await asyncio.sleep(0.005)
49
50if __name__ == '__main__':
51    curses.wrapper(main)

Libraries

Progress Bar

1# $ pip3 install tqdm
2>>> import tqdm, time
3>>> for el in tqdm.tqdm([1, 2, 3], desc='Processing'):
4...     time.sleep(1)
5Processing: 100%|████████████████████| 3/3 [00:03<00:00,  1.00s/it]

Plot

1# $ pip3 install matplotlib
2import matplotlib.pyplot as plt
3
4plt.plot/bar/scatter(x_data, y_data [, label=<str>])  # Or: plt.plot(y_data)
5plt.legend()                                          # Adds a legend.
6plt.savefig(<path>)                                   # Saves the figure.
7plt.show()                                            # Displays the figure.
8plt.clf()                                             # Clears the figure.

Table

Prints a CSV spreadsheet to the console:

1# $ pip3 install tabulate
2import csv, tabulate
3with open('test.csv', encoding='utf-8', newline='') as file:
4    rows = list(csv.reader(file))
5print(tabulate.tabulate(rows, headers='firstrow'))

Curses

Runs a basic file explorer in the console:

 1# $ pip3 install windows-curses
 2import curses, os
 3from curses import A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER
 4
 5def main(screen):
 6    ch, first, selected, paths = 0, 0, 0, os.listdir()
 7    while ch != ord('q'):
 8        height, width = screen.getmaxyx()
 9        screen.erase()
10        for y, filename in enumerate(paths[first : first+height]):
11            color = A_REVERSE if filename == paths[selected] else 0
12            screen.addnstr(y, 0, filename, width-1, color)
13        ch = screen.getch()
14        selected += (ch == KEY_DOWN) - (ch == KEY_UP)
15        selected = max(0, min(len(paths)-1, selected))
16        first += (selected >= first + height) - (selected < first)
17        if ch in [KEY_LEFT, KEY_RIGHT, KEY_ENTER, ord('\n'), ord('\r')]:
18            new_dir = '..' if ch == KEY_LEFT else paths[selected]
19            if os.path.isdir(new_dir):
20                os.chdir(new_dir)
21                first, selected, paths = 0, 0, os.listdir()
22
23if __name__ == '__main__':
24    curses.wrapper(main)

PySimpleGUI

A weight converter GUI application:

 1# $ pip3 install PySimpleGUI
 2import PySimpleGUI as sg
 3
 4text_box = sg.Input(default_text='100', enable_events=True, key='-VALUE-')
 5dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='-UNIT-')
 6label    = sg.Text('100 kg is 220.462 lbs.', key='-OUTPUT-')
 7button   = sg.Button('Close')
 8window   = sg.Window('Weight Converter', [[text_box, dropdown], [label], [button]])
 9
10while True:
11    event, values = window.read()
12    if event in [sg.WIN_CLOSED, 'Close']:
13        break
14    try:
15        value = float(values['-VALUE-'])
16    except ValueError:
17        continue
18    unit = values['-UNIT-']
19    factors = {'g': 0.001, 'kg': 1, 't': 1000}
20    lbs = value * factors[unit] / 0.45359237
21    window['-OUTPUT-'].update(value=f'{value} {unit} is {lbs:g} lbs.')
22window.close()

Scraping

Scrapes Python's URL and logo from its Wikipedia page:

 1# $ pip3 install requests beautifulsoup4
 2import requests, bs4, os
 3
 4response   = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)')
 5document   = bs4.BeautifulSoup(response.text, 'html.parser')
 6table      = document.find('table', class_='infobox vevent')
 7python_url = table.find('th', text='Website').next_sibling.a['href']
 8logo_url   = table.find('img')['src']
 9logo       = requests.get(f'https:{logo_url}').content
10filename   = os.path.basename(logo_url)
11with open(filename, 'wb') as file:
12    file.write(logo)
13print(f'{python_url}, file://{os.path.abspath(filename)}')

Selenium

Library for scraping websites with dynamic content.

1# $ pip3 install selenium
2from selenium import webdriver
3
4<Drv> = webdriver.Chrome/Firefox/Safari/Edge()         # Opens the browser. Also <Drv>.quit().
5<Drv>.get('<url>')                                     # Also <Drv>.implicitly_wait(seconds).
6<El> = <Drv/El>.find_element('css selector', '<css>')  # '<tag>#<id>.<class>[<attr>="<val>"]'.
7<list> = <Drv/El>.find_elements('xpath', '<xpath>')    # '//<tag>[@<attr>="<val>"]'.
8<str> = <El>.get_attribute/get_property(<str>)         # Also <El>.text/tag_name.
9<El>.click/clear()                                     # Also <El>.send_keys(<str>).

XPath — also available in browser's console via '$x(<xpath>)' and by lxml library:

1<xpath>     = //<element>[/ or // <element>]           # Child: /, Descendant: //, Parent: /..
2<xpath>     = //<element>/following::<element>         # Next sibling. Also preceding/parent/…
3<element>   = <tag><conditions><index>                 # `<tag> = */a/…`, `<index> = [1/2/…]`.
4<condition> = [<sub_cond> [and/or <sub_cond>]]         # For negation use `not(<sub_cond>)`.
5<sub_cond>  = @<attr>="<val>"                          # `.="<val>"` matches complete text.
6<sub_cond>  = contains(@<attr>, "<val>")               # Is <val> a substring of attr's value?
7<sub_cond>  = [//]<element>                            # Has matching child? Descendant if //.

Web

Flask is a micro web framework/server. If you just want to open a html file in a web browser use 'webbrowser.open(<path>)' instead.

1# $ pip3 install flask
2import flask
1app = flask.Flask(__name__)                # Returns app object. Put at the top.
2app.run(host=None, port=None, debug=None)  # Or: `$ flask --app <module> run`
  • Starts the app at 'http://localhost:5000'. Use 'host="0.0.0.0"' to run externally.
  • Install a WSGI server like Waitress and a HTTP server such as Nginx for better security.
  • Debug mode restarts the app whenever script changes and displays errors in the browser.

Static Request

1@app.route('/img/<path:filename>')
2def serve_file(filename):
3    return flask.send_from_directory('dirname/', filename)

Dynamic Request

1@app.route('/<sport>')
2def serve_html(sport):
3    return flask.render_template_string('<h1>{{title}}</h1>', title=sport)
  • Use 'render_template(filename, <kwargs>)' to render file located in templates dir.
  • To return an error code use 'abort(<int>)' and to redirect use 'redirect(<url>)'.
  • 'request.args[<str>]' returns parameter from the query string (URL part after '?').
  • 'session[<str>] = <obj>' stores session data. Needs 'app.secret_key = <str>'.

REST Request

1@app.post('/<sport>/odds')
2def serve_json(sport):
3    team = flask.request.form['team']
4    return {'team': team, 'odds': [2.09, 3.74, 3.68]}

Starts the app in its own thread and queries its REST API:

1# $ pip3 install requests
2>>> import threading, requests
3>>> threading.Thread(target=app.run, daemon=True).start()
4>>> url = 'http://localhost:5000/football/odds'
5>>> request_data = {'team': 'arsenal f.c.'}
6>>> response = requests.post(url, data=request_data)
7>>> response.json()
8{'team': 'arsenal f.c.', 'odds': [2.09, 3.74, 3.68]}

Profiling

1from time import perf_counter
2start_time = perf_counter()
3...
4duration_in_seconds = perf_counter() - start_time

Timing a Snippet

1>>> from timeit import timeit
2>>> timeit('list(range(10000))', number=1000, globals=globals(), setup='pass')
30.19373

Profiling by Line

 1$ pip3 install line_profiler
 2$ echo '@profile
 3def main():
 4    a = list(range(10000))
 5    b = set(range(10000))
 6main()' > test.py
 7$ kernprof -lv test.py
 8Line #      Hits         Time  Per Hit   % Time  Line Contents
 9==============================================================
10     1                                           @profile
11     2                                           def main():
12     3         1        253.4    253.4     32.2      a = list(range(10000))
13     4         1        534.1    534.1     67.8      b = set(range(10000))

Call and Flame Graphs

1$ apt/brew install graphviz && pip3 install gprof2dot snakeviz  # Or download installer.
2$ tail --lines=+2 test.py > test.py                             # Removes first line.
3$ python3 -m cProfile -o test.prof test.py                      # Runs built-in profiler.
4$ gprof2dot --format=pstats test.prof | dot -T png -o test.png  # Generates call graph.
5$ xdg-open/open test.png                                        # Displays call graph.
6$ snakeviz test.prof                                            # Displays flame graph.

Sampling and Memory Profilers

1+--------------+------------+-------------------------------+-------+------+
2| pip3 install |   Target   |          How to run           | Lines | Live |
3+--------------+------------+-------------------------------+-------+------+
4| pyinstrument |    CPU     | pyinstrument test.py          |  No   | No   |
5| py-spy       |    CPU     | py-spy top -- python3 test.py |  No   | Yes  |
6| scalene      | CPU+Memory | scalene test.py               |  Yes  | No   |
7| memray       |   Memory   | memray run --live test.py     |  Yes  | Yes  |
8+--------------+------------+-------------------------------+-------+------+

NumPy

Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code. An even faster alternative that runs on a GPU is called CuPy.

1# $ pip3 install numpy
2import numpy as np
1<array> = np.array(<list/list_of_lists/>)              # Returns a 1d/2d/… NumPy array.
2<array> = np.zeros/ones/empty(<shape>)                  # Also np.full(<shape>, <el>).
3<array> = np.arange(from_inc, to_exc, ±step)            # Also np.linspace(start, stop, len).
4<array> = np.random.randint(from_inc, to_exc, <shape>)  # Also np.random.random(<shape>).
1<view>  = <array>.reshape(<shape>)                      # Also `<array>.shape = <shape>`.
2<array> = <array>.flatten()                             # Also `<view> = <array>.ravel()`.
3<view>  = <array>.transpose()                           # Or: <array>.T
1<array> = np.copy/abs/sqrt/log/int64(<array>)           # Returns new array of the same shape.
2<array> = <array>.sum/max/mean/argmax/all(axis)         # Aggregates specified dimension.
3<array> = np.apply_along_axis(<func>, axis, <array>)    # Func can return a scalar or array.
1<array> = np.concatenate(<list_of_arrays>, axis=0)      # Links arrays along first axis (rows).
2<array> = np.row_stack/column_stack(<list_of_arrays>)   # Treats 1d arrays as rows or columns.
3<array> = np.tile/repeat(<array>, <int/list> [, axis])  # Tiles array or repeats its elements.
  • Shape is a tuple of dimension sizes. A 100x50 RGB image has shape (50, 100, 3).
  • Axis is an index of a dimension. Leftmost dimension has index 0. Summing the RGB image along axis 2 will return a greyscale image with shape (50, 100).

Indexing

1<el>       = <2d>[row_index, col_index]                 # Or: <3d>[<int>, <int>, <int>]
2<1d_view>  = <2d>[row_index]                            # Or: <3d>[<int>, <int>, <slice>]
3<1d_view>  = <2d>[:, col_index]                         # Or: <3d>[<int>, <slice>, <int>]
4<2d_view>  = <2d>[from:to_row_i, from:to_col_i]         # Or: <3d>[<int>, <slice>, <slice>]
1<1d_array> = <2d>[row_indices, col_indices]             # Or: <3d>[<int/1d>, <1d>, <1d>]
2<2d_array> = <2d>[row_indices]                          # Or: <3d>[<int/1d>, <1d>, <slice>]
3<2d_array> = <2d>[:, col_indices]                       # Or: <3d>[<int/1d>, <slice>, <1d>]
4<2d_array> = <2d>[np.ix_(row_indices, col_indices)]     # Or: <3d>[<int/1d/2d>, <2d>, <2d>]
1<2d_bools> = <2d> > <el/1d/2d>                          # 1d object must have size of a row.
2<1/2d_arr> = <2d>[<2d/1d_bools>]                        # 1d_bools must have size of a column.
  • ':' returns a slice of all dimension's indices. Omitted dimensions default to ':'.
  • Indices should not be tuples because Python converts 'obj[i, j]' to 'obj[(i, j)]'!
  • 'ix_()' returns two 2d arrays. Indices of different shapes get unified with broadcasting.
  • Any value that is broadcastable to the indexed shape can be assigned to the selection.

Broadcasting

Set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.

1left  = [[0.1], [0.6], [0.8]]                           # Shape: (3, 1)
2right = [ 0.1 ,  0.6 ,  0.8 ]                           # Shape: (3,)

1. If array shapes differ in length, left-pad the shorter shape with ones:

1left  = [[0.1], [0.6], [0.8]]                           # Shape: (3, 1)
2right = [[0.1 ,  0.6 ,  0.8]]                           # Shape: (1, 3) <- !

2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:

1left  = [[0.1,  0.1,  0.1],                             # Shape: (3, 3) <- !
2         [0.6,  0.6,  0.6],
3         [0.8,  0.8,  0.8]]
4
5right = [[0.1,  0.6,  0.8],                             # Shape: (3, 3) <- !
6         [0.1,  0.6,  0.8],
7         [0.1,  0.6,  0.8]]

Example

For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

 1>>> points = np.array([0.1, 0.6, 0.8])
 2 [ 0.1,  0.6,  0.8]
 3>>> wrapped_points = points.reshape(3, 1)
 4[[ 0.1],
 5 [ 0.6],
 6 [ 0.8]]
 7>>> distances = wrapped_points - points
 8[[ 0. , -0.5, -0.7],
 9 [ 0.5,  0. , -0.2],
10 [ 0.7,  0.2,  0. ]]
11>>> distances = np.abs(distances)
12[[ 0. ,  0.5,  0.7],
13 [ 0.5,  0. ,  0.2],
14 [ 0.7,  0.2,  0. ]]
15>>> distances[range(3), range(3)] = np.inf
16[[ inf,  0.5,  0.7],
17 [ 0.5,  inf,  0.2],
18 [ 0.7,  0.2,  inf]]
19>>> distances.argmin(1)
20[1, 2, 1]

Image

1# $ pip3 install pillow
2from PIL import Image
1<Image> = Image.new('<mode>', (width, height))  # Also `color=<int/tuple/str>`.
2<Image> = Image.open(<path>)                    # Identifies format based on file contents.
3<Image> = <Image>.convert('<mode>')             # Converts image to the new mode.
4<Image>.save(<path>)                            # Selects format based on the path extension.
5<Image>.show()                                  # Opens image in the default preview app.
1<int/tuple> = <Image>.getpixel((x, y))          # Returns pixel's value (its color).
2<Image>.putpixel((x, y), <int/tuple>)           # Updates pixel's value.
3<ImagingCore> = <Image>.getdata()               # Returns a flattened view of pixel values.
4<Image>.putdata(<list/ImagingCore>)             # Updates pixels with a copy of the sequence.
5<Image>.paste(<Image>, (x, y))                  # Draws passed image at specified location.
1<Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>(<args>)`
2<Image> = <Enhance>.enhance(<float>)            # `<Enhance> = ImageEnhance.<name>(<Image>)`
1<array> = np.array(<Image>)                     # Creates a 2d/3d NumPy array from the image.
2<Image> = Image.fromarray(np.uint8(<array>))    # Use `<array>.clip(0, 255)` to clip values.

Modes

  • 'L' - 8-bit pixels, greyscale.
  • 'RGB' - 3x8-bit pixels, true color.
  • 'RGBA' - 4x8-bit pixels, true color with transparency mask.
  • 'HSV' - 3x8-bit pixels, Hue, Saturation, Value color space.

Examples

Creates a PNG image of a rainbow gradient:

1WIDTH, HEIGHT = 100, 100
2n_pixels = WIDTH * HEIGHT
3hues = (255 * i/n_pixels for i in range(n_pixels))
4img = Image.new('HSV', (WIDTH, HEIGHT))
5img.putdata([(int(h), 255, 255) for h in hues])
6img.convert('RGB').save('test.png')

Adds noise to the PNG image and displays it:

1from random import randint
2add_noise = lambda value: max(0, min(255, value + randint(-20, 20)))
3img = Image.open('test.png').convert('HSV')
4img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
5img.show()

Image Draw

1from PIL import ImageDraw
2<ImageDraw> = ImageDraw.Draw(<Image>)           # Object for adding 2D graphics to the image.
3<ImageDraw>.point((x, y))                       # Draws a point. Truncates floats into ints.
4<ImageDraw>.line((x1, y1, x2, y2 [, ...]))      # To get anti-aliasing use Image's resize().
5<ImageDraw>.arc((x1, y1, x2, y2), deg1, deg2)   # Always draws in clockwise direction.
6<ImageDraw>.rectangle((x1, y1, x2, y2))         # To rotate use Image's rotate() and paste().
7<ImageDraw>.polygon((x1, y1, x2, y2, ...))      # Last point gets connected to the first.
8<ImageDraw>.ellipse((x1, y1, x2, y2))           # To rotate use Image's rotate() and paste().
9<ImageDraw>.text((x, y), <str>, font=<Font>)    # `<Font> = ImageFont.truetype(<path>, size)`
  • Use 'fill=<color>' to set the primary color.
  • Use 'width=<int>' to set the width of lines or contours.
  • Use 'outline=<color>' to set the color of the contours.
  • Color can be an int, tuple, '#rrggbb[aa]' string or a color name.

Animation

Creates a GIF of a bouncing ball:

 1# $ pip3 install imageio
 2from PIL import Image, ImageDraw
 3import imageio
 4
 5WIDTH, HEIGHT, R = 126, 126, 10
 6frames = []
 7for velocity in range(1, 16):
 8    y = sum(range(velocity))
 9    frame = Image.new('L', (WIDTH, HEIGHT))
10    draw = ImageDraw.Draw(frame)
11    draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+R*2), fill='white')
12    frames.append(frame)
13frames += reversed(frames[1:-1])
14imageio.mimsave('test.gif', frames, duration=0.03)

Audio

1import wave
1<Wave>  = wave.open('<path>', 'rb')   # Opens the WAV file.
2<int>   = <Wave>.getframerate()       # Returns number of frames per second.
3<int>   = <Wave>.getnchannels()       # Returns number of samples per frame.
4<int>   = <Wave>.getsampwidth()       # Returns number of bytes per sample.
5<tuple> = <Wave>.getparams()          # Returns namedtuple of all parameters.
6<bytes> = <Wave>.readframes(nframes)  # Returns next n frames. All if -1.
1<Wave> = wave.open('<path>', 'wb')    # Creates/truncates a file for writing.
2<Wave>.setframerate(<int>)            # Pass 44100 for CD, 48000 for video.
3<Wave>.setnchannels(<int>)            # Pass 1 for mono, 2 for stereo.
4<Wave>.setsampwidth(<int>)            # Pass 2 for CD, 3 for hi-res sound.
5<Wave>.setparams(<tuple>)             # Sets all parameters.
6<Wave>.writeframes(<bytes>)           # Appends frames to the file.
  • Bytes object contains a sequence of frames, each consisting of one or more samples.
  • In a stereo signal, the first sample of a frame belongs to the left channel.
  • Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.
  • If sample width is one byte, then the integer should be encoded unsigned.
  • For all other sizes, the integer should be encoded signed with little-endian byte order.

Sample Values

1+-----------+-----------+------+-----------+
2| sampwidth |    min    | zero |    max    |
3+-----------+-----------+------+-----------+
4|     1     |         0 |  128 |       255 |
5|     2     |    -32768 |    0 |     32767 |
6|     3     |  -8388608 |    0 |   8388607 |
7+-----------+-----------+------+-----------+

Read Float Samples from WAV File

1def read_wav_file(filename):
2    def get_int(bytes_obj):
3        an_int = int.from_bytes(bytes_obj, 'little', signed=(sampwidth != 1))
4        return an_int - 128 * (sampwidth == 1)
5    with wave.open(filename, 'rb') as file:
6        sampwidth = file.getsampwidth()
7        frames = file.readframes(-1)
8    bytes_samples = (frames[i : i+sampwidth] for i in range(0, len(frames), sampwidth))
9    return [get_int(b) / pow(2, sampwidth * 8 - 1) for b in bytes_samples]

Write Float Samples to WAV File

 1def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framerate=44100):
 2    def get_bytes(a_float):
 3        a_float = max(-1, min(1 - 2e-16, a_float))
 4        a_float += sampwidth == 1
 5        a_float *= pow(2, sampwidth * 8 - 1)
 6        return int(a_float).to_bytes(sampwidth, 'little', signed=(sampwidth != 1))
 7    with wave.open(filename, 'wb') as file:
 8        file.setnchannels(nchannels)
 9        file.setsampwidth(sampwidth)
10        file.setframerate(framerate)
11        file.writeframes(b''.join(get_bytes(f) for f in float_samples))

Examples

Saves a 440 Hz sine wave to a mono WAV file:

1from math import pi, sin
2samples_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100_000))
3write_to_wav_file('test.wav', samples_f)

Adds noise to the mono WAV file:

1from random import random
2add_noise = lambda value: value + (random() - 0.5) * 0.03
3samples_f = (add_noise(f) for f in read_wav_file('test.wav'))
4write_to_wav_file('test.wav', samples_f)

Plays the WAV file:

1# $ pip3 install simpleaudio
2from simpleaudio import play_buffer
3with wave.open('test.wav', 'rb') as file:
4    p = file.getparams()
5    frames = file.readframes(-1)
6    play_buffer(frames, p.nchannels, p.sampwidth, p.framerate).wait_done()

Text to Speech

1# $ pip3 install pyttsx3
2import pyttsx3
3engine = pyttsx3.init()
4engine.say('Sally sells seashells by the seashore.')
5engine.runAndWait()

Synthesizer

Plays Popcorn by Gershon Kingsley:

 1# $ pip3 install simpleaudio
 2import array, itertools as it, math, simpleaudio
 3
 4F  = 44100
 5P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
 6P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
 7get_pause   = lambda seconds: it.repeat(0, int(seconds * F))
 8sin_f       = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
 9get_wave    = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
10get_hz      = lambda note: 8.176 * 2 ** (int(note[:2]) / 12)
11get_sec     = lambda note: 1/4 if '♩' in note else 1/8
12get_samples = lambda note: get_wave(get_hz(note), get_sec(note)) if note else get_pause(1/8)
13samples_f   = it.chain.from_iterable(get_samples(n) for n in (P1+P2).split(','))
14samples_i   = array.array('h', (int(f * 30000) for f in samples_f))
15simpleaudio.play_buffer(samples_i, 1, 2, F).wait_done()

Pygame

 1# $ pip3 install pygame
 2import pygame as pg
 3
 4pg.init()
 5screen = pg.display.set_mode((500, 500))
 6rect = pg.Rect(240, 240, 20, 20)
 7while not pg.event.get(pg.QUIT):
 8    deltas = {pg.K_UP: (0, -20), pg.K_RIGHT: (20, 0), pg.K_DOWN: (0, 20), pg.K_LEFT: (-20, 0)}
 9    for event in pg.event.get(pg.KEYDOWN):
10        dx, dy = deltas.get(event.key, (0, 0))
11        rect = rect.move((dx, dy))
12    screen.fill((0, 0, 0))
13    pg.draw.rect(screen, (255, 255, 255), rect)
14    pg.display.flip()

Rectangle

Object for storing rectangular coordinates.

1<Rect> = pg.Rect(x, y, width, height)           # Floats get truncated into ints.
2<int>  = <Rect>.x/y/centerx/centery/           # Top, right, bottom, left. Allows assignments.
3<tup.> = <Rect>.topleft/center/                # Topright, bottomright, bottomleft. Same.
4<Rect> = <Rect>.move((delta_x, delta_y))        # Use move_ip() to move in-place.
1<bool> = <Rect>.collidepoint((x, y))            # Checks if rectangle contains the point.
2<bool> = <Rect>.colliderect(<Rect>)             # Checks if the two rectangles overlap.
3<int>  = <Rect>.collidelist(<list_of_Rect>)     # Returns index of first colliding Rect or -1.
4<list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding rectangles.

Surface

Object for representing images.

1<Surf> = pg.display.set_mode((width, height))   # Opens new window and returns its surface.
2<Surf> = pg.Surface((width, height))            # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
3<Surf> = pg.image.load(<path/file>)             # Loads the image. Format depends on source.
4<Surf> = pg.surfarray.make_surface(<np_array>)  # Also `<np_arr> = surfarray.pixels3d(<Surf>)`.
5<Surf> = <Surf>.subsurface(<Rect>)              # Creates a new surface from the cutout.
1<Surf>.fill(color)                              # Tuple, Color('#rrggbb[aa]') or Color(<name>).
2<Surf>.set_at((x, y), color)                    # Updates pixel. Also <Surf>.get_at((x, y)).
3<Surf>.blit(<Surf>, (x, y))                     # Draws passed surface at specified location.
1from pygame.transform import scale, ...
2<Surf> = scale(<Surf>, (width, height))         # Returns scaled surface.
3<Surf> = rotate(<Surf>, anticlock_degrees)      # Returns rotated and scaled surface.
4<Surf> = flip(<Surf>, x_bool, y_bool)           # Returns flipped surface.
1from pygame.draw import line, ...
2line(<Surf>, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
3arc(<Surf>, color, <Rect>, from_rad, to_rad)    # Also ellipse(<Surf>, color, <Rect>, width=0).
4rect(<Surf>, color, <Rect>, width=0)            # Also polygon(<Surf>, color, points, width=0).

Font

1<Font> = pg.font.Font(<path/file>, size)        # Loads TTF file. Pass None for default font.
2<Surf> = <Font>.render(text, antialias, color)  # Background color can be specified at the end.

Sound

1<Sound> = pg.mixer.Sound(<path/file/bytes>)     # WAV file or bytes/array of signed shorts.
2<Sound>.play/stop()                             # Also set_volume(<float>), fadeout(msec).

Basic Mario Brothers Example

 1import collections, dataclasses, enum, io, itertools as it, pygame as pg, urllib.request
 2from random import randint
 3
 4P = collections.namedtuple('P', 'x y')          # Position
 5D = enum.Enum('D', 'n e s w')                   # Direction
 6W, H, MAX_S = 50, 50, P(5, 10)                  # Width, Height, Max speed
 7
 8def main():
 9    def get_screen():
10        pg.init()
11        return pg.display.set_mode((W*16, H*16))
12    def get_images():
13        url = 'https://gto76.github.io/python-cheatsheet/web/mario_bros.png'
14        img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read()))
15        return [img.subsurface(get_rect(x, 0)) for x in range(img.get_width() // 16)]
16    def get_mario():
17        Mario = dataclasses.make_dataclass('Mario', 'rect spd facing_left frame_cycle'.split())
18        return Mario(get_rect(1, 1), P(0, 0), False, it.cycle(range(3)))
19    def get_tiles():
20        border = [(x, y) for x in range(W) for y in range(H) if x in [0, W-1] or y in [0, H-1]]
21        platforms = [(randint(1, W-2), randint(2, H-2)) for _ in range(W*H // 10)]
22        return [get_rect(x, y) for x, y in border + platforms]
23    def get_rect(x, y):
24        return pg.Rect(x*16, y*16, 16, 16)
25    run(get_screen(), get_images(), get_mario(), get_tiles())
26
27def run(screen, images, mario, tiles):
28    clock = pg.time.Clock()
29    pressed = set()
30    while not pg.event.get(pg.QUIT) and clock.tick(28):
31        keys = {pg.K_UP: D.n, pg.K_RIGHT: D.e, pg.K_DOWN: D.s, pg.K_LEFT: D.w}
32        pressed |= {keys.get(e.key) for e in pg.event.get(pg.KEYDOWN)}
33        pressed -= {keys.get(e.key) for e in pg.event.get(pg.KEYUP)}
34        update_speed(mario, tiles, pressed)
35        update_position(mario, tiles)
36        draw(screen, images, mario, tiles, pressed)
37
38def update_speed(mario, tiles, pressed):
39    x, y = mario.spd
40    x += 2 * ((D.e in pressed) - (D.w in pressed))
41    x += (x < 0) - (x > 0)
42    y += 1 if D.s not in get_boundaries(mario.rect, tiles) else (D.n in pressed) * -10
43    mario.spd = P(x=max(-MAX_S.x, min(MAX_S.x, x)), y=max(-MAX_S.y, min(MAX_S.y, y)))
44
45def update_position(mario, tiles):
46    x, y = mario.rect.topleft
47    n_steps = max(abs(s) for s in mario.spd)
48    for _ in range(n_steps):
49        mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))
50        mario.rect.topleft = x, y = x + (mario.spd.x / n_steps), y + (mario.spd.y / n_steps)
51
52def get_boundaries(rect, tiles):
53    deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
54    return {d for d, delta in deltas.items() if rect.move(delta).collidelist(tiles) != -1}
55
56def stop_on_collision(spd, bounds):
57    return P(x=0 if (D.w in bounds and spd.x < 0) or (D.e in bounds and spd.x > 0) else spd.x,
58             y=0 if (D.n in bounds and spd.y < 0) or (D.s in bounds and spd.y > 0) else spd.y)
59
60def draw(screen, images, mario, tiles, pressed):
61    def get_marios_image_index():
62        if D.s not in get_boundaries(mario.rect, tiles):
63            return 4
64        return next(mario.frame_cycle) if {D.w, D.e} & pressed else 6
65    screen.fill((85, 168, 255))
66    mario.facing_left = (D.w in pressed) if {D.w, D.e} & pressed else mario.facing_left
67    screen.blit(images[get_marios_image_index() + mario.facing_left * 9], mario.rect)
68    for t in tiles:
69        screen.blit(images[18 if t.x in [0, (W-1)*16] or t.y in [0, (H-1)*16] else 19], t)
70    pg.display.flip()
71
72if __name__ == '__main__':
73    main()

Pandas

1# $ pip3 install pandas matplotlib
2import pandas as pd, matplotlib.pyplot as plt

Series

Ordered dictionary with a name.

1>>> pd.Series([1, 2], index=['x', 'y'], name='a')
2x    1
3y    2
4Name: a, dtype: int64
1<Sr> = pd.Series(<list>)                       # Assigns RangeIndex starting at 0.
2<Sr> = pd.Series(<dict>)                       # Takes dictionary's keys for index.
3<Sr> = pd.Series(<dict/Series>, index=<list>)  # Only keeps items with keys specified in index.
1<el> = <Sr>.loc[key]                           # Or: <Sr>.iloc[i]
2<Sr> = <Sr>.loc[coll_of_keys]                  # Or: <Sr>.iloc[coll_of_i]
3<Sr> = <Sr>.loc[from_key : to_key_inc]         # Or: <Sr>.iloc[from_i : to_i_exc]
1<el> = <Sr>[key/i]                             # Or: <Sr>.<key>
2<Sr> = <Sr>[coll_of_keys/coll_of_i]            # Or: <Sr>[key/i : key/i]
3<Sr> = <Sr>[bools]                             # Or: <Sr>.loc/iloc[bools]
1<Sr> = <Sr> > <el/Sr>                          # Returns a Series of bools.
2<Sr> = <Sr> + <el/Sr>                          # Items with non-matching keys get value NaN.
1<Sr> = pd.concat(<coll_of_Sr>)                 # Concats multiple series into one long Series.
2<Sr> = <Sr>.combine_first(<Sr>)                # Adds items that are not yet present.
3<Sr>.update(<Sr>)                              # Updates items that are already present.
1<Sr>.plot.line/area/bar/pie/hist()             # Generates a Matplotlib plot.
2plt.show()                                     # Displays the plot. Also plt.savefig(<path>).

Series — Aggregate, Transform, Map:

1<el> = <Sr>.sum/max/mean/idxmax/all()          # Or: <Sr>.agg(lambda <Sr>: <el>)
2<Sr> = <Sr>.rank/diff/cumsum/ffill/interpo()  # Or: <Sr>.agg/transform(lambda <Sr>: <Sr>)
3<Sr> = <Sr>.fillna(<el>)                       # Or: <Sr>.agg/transform/map(lambda <el>: <el>)
1>>> sr = pd.Series([2, 3], index=['x', 'y'])
2x    2
3y    3
1+---------------+-------------+-------------+---------------+
2|               |    'sum'    |   ['sum']   | {'s': 'sum'}  |
3+---------------+-------------+-------------+---------------+
4| sr.apply(…)   |      5      |    sum  5   |     s  5      |
5| sr.agg(…)     |             |             |               |
6+---------------+-------------+-------------+---------------+
1+---------------+-------------+-------------+---------------+
2|               |    'rank'   |   ['rank']  | {'r': 'rank'} |
3+---------------+-------------+-------------+---------------+
4| sr.apply(…)   |             |      rank   |               |
5| sr.agg(…)     |     x  1    |   x     1   |    r  x  1    |
6|               |     y  2    |   y     2   |       y  2    |
7+---------------+-------------+-------------+---------------+
  • Indexing objects can't be tuples because 'obj[x, y]' is converted to 'obj[(x, y)]'!
  • Methods ffill(), interpolate(), fillna() and dropna() accept 'inplace=True'.
  • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.

DataFrame

Table with labeled rows and columns.

1>>> pd.DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
2   x  y
3a  1  2
4b  3  4
1<DF>    = pd.DataFrame(<list_of_rows>)         # Rows can be either lists, dicts or series.
2<DF>    = pd.DataFrame(<dict_of_columns>)      # Columns can be either lists, dicts or series.
1<el>    = <DF>.loc[row_key, col_key]           # Or: <DF>.iloc[row_i, col_i]
2<Sr/DF> = <DF>.loc[row_key/s]                  # Or: <DF>.iloc[row_i/s]
3<Sr/DF> = <DF>.loc[:, col_key/s]               # Or: <DF>.iloc[:, col_i/s]
4<DF>    = <DF>.loc[row_bools, col_bools]       # Or: <DF>.iloc[row_bools, col_bools]
1<Sr/DF> = <DF>[col_key/s]                      # Or: <DF>.<col_key>
2<DF>    = <DF>[row_bools]                      # Keeps rows as specified by bools.
3<DF>    = <DF>[<DF_of_bools>]                  # Assigns NaN to items that are False in bools.
1<DF>    = <DF> > <el/Sr/DF>                    # Returns DF of bools. Sr is treated as a row.
2<DF>    = <DF> + <el/Sr/DF>                    # Items with non-matching keys get value NaN.
1<DF>    = <DF>.set_index(col_key)              # Replaces row keys with column's values.
2<DF>    = <DF>.reset_index(drop=False)         # Drops or moves row keys to column named index.
3<DF>    = <DF>.sort_index(ascending=True)      # Sorts rows by row keys. Use `axis=1` for cols.
4<DF>    = <DF>.sort_values(col_key/s)          # Sorts rows by passed column/s. Also `axis=1`.

DataFrame — Merge, Join, Concat:

1>>> l = pd.DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
2   x  y
3a  1  2
4b  3  4
5>>> r = pd.DataFrame([[4, 5], [6, 7]], index=['b', 'c'], columns=['y', 'z'])
6   y  z
7b  4  5
8c  6  7
 1+------------------------+---------------+------------+------------+--------------------------+
 2|                        |    'outer'    |   'inner'  |   'left'   |       Description        |
 3+------------------------+---------------+------------+------------+--------------------------+
 4| l.merge(r, on='y',     |    x   y   z  | x   y   z  | x   y   z  | Merges on column if 'on' |
 5|            how=…)      | 0  1   2   .  | 3   4   5  | 1   2   .  | or 'left/right_on' are   |
 6|                        | 1  3   4   5  |            | 3   4   5  | set, else on shared cols.|
 7|                        | 2  .   6   7  |            |            | Uses 'inner' by default. |
 8+------------------------+---------------+------------+------------+--------------------------+
 9| l.join(r, lsuffix='l', |    x yl yr  z |            | x yl yr  z | Merges on row keys.      |
10|           rsuffix='r', | a  1  2  .  . | x yl yr  z | 1  2  .  . | Uses 'left' by default.  |
11|           how=…)       | b  3  4  4  5 | 3  4  4  5 | 3  4  4  5 | If r is a Series, it is  |
12|                        | c  .  .  6  7 |            |            | treated as a column.     |
13+------------------------+---------------+------------+------------+--------------------------+
14| pd.concat([l, r],      |    x   y   z  |     y      |            | Adds rows at the bottom. |
15|           axis=0,      | a  1   2   .  |     2      |            | Uses 'outer' by default. |
16|           join=…)      | b  3   4   .  |     4      |            | A Series is treated as a |
17|                        | b  .   4   5  |     4      |            | column. To add a row use |
18|                        | c  .   6   7  |     6      |            | pd.concat([l, DF([sr])]).|
19+------------------------+---------------+------------+------------+--------------------------+
20| pd.concat([l, r],      |    x  y  y  z |            |            | Adds columns at the      |
21|           axis=1,      | a  1  2  .  . | x  y  y  z |            | right end. Uses 'outer'  |
22|           join=…)      | b  3  4  4  5 | 3  4  4  5 |            | by default. A Series is  |
23|                        | c  .  .  6  7 |            |            | treated as a column.     |
24+------------------------+---------------+------------+------------+--------------------------+
25| l.combine_first(r)     |    x   y   z  |            |            | Adds missing rows and    |
26|                        | a  1   2   .  |            |            | columns. Also updates    |
27|                        | b  3   4   5  |            |            | items that contain NaN.  |
28|                        | c  .   6   7  |            |            | Argument r must be a DF. |
29+------------------------+---------------+------------+------------+--------------------------+

DataFrame — Aggregate, Transform, Map:

1<Sr> = <DF>.sum/max/mean/idxmax/all()          # Or: <DF>.apply/agg(lambda <Sr>: <el>)
2<DF> = <DF>.rank/diff/cumsum/ffill/interpo()  # Or: <DF>.apply/agg/transfo…(lambda <Sr>: <Sr>)
3<DF> = <DF>.fillna(<el>)                       # Or: <DF>.applymap(lambda <el>: <el>)
  • All operations operate on columns by default. Pass 'axis=1' to process the rows instead.
1>>> df = pd.DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
2   x  y
3a  1  2
4b  3  4
1+-----------------+-------------+-------------+---------------+
2|                 |    'sum'    |   ['sum']   | {'x': 'sum'}  |
3+-----------------+-------------+-------------+---------------+
4| df.apply(…)     |     x  4    |       x  y  |     x  4      |
5| df.agg(…)       |     y  6    |  sum  4  6  |               |
6+-----------------+-------------+-------------+---------------+
1+-----------------+-------------+-------------+---------------+
2|                 |    'rank'   |   ['rank']  | {'x': 'rank'} |
3+-----------------+-------------+-------------+---------------+
4| df.apply(…)     |             |      x    y |               |
5| df.agg(…)       |      x  y   |   rank rank |        x      |
6| df.transform(…) |   a  1  1   | a    1    1 |     a  1      |
7|                 |   b  2  2   | b    2    2 |     b  2      |
8+-----------------+-------------+-------------+---------------+
  • Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result's values.

DataFrame — Plot, Encode, Decode:

1<DF>.plot.line/area/bar/scatter(x=col_key, )  # `y=col_key/s`. Also hist/box(by=col_key).
2plt.show()                                     # Displays the plot. Also plt.savefig(<path>).
1<DF> = pd.read_json/html('<str/path/url>')     # Run `$ pip3 install beautifulsoup4 lxml`.
2<DF> = pd.read_csv('<path/url>')               # `header/index_col/dtype/parse_dates=<obj>`.
3<DF> = pd.read_pickle/excel('<path/url>')      # Use `sheet_name=None` to get all Excel sheets.
4<DF> = pd.read_sql('<table/query>', <conn.>)   # SQLite3/SQLAlchemy connection (see #SQLite).
1<dict> = <DF>.to_dict('d/l/s/…')               # Returns columns as dicts, lists or series.
2<str>  = <DF>.to_json/html/csv/latex()         # Saves output to file if path is passed.
3<DF>.to_pickle/excel(<path>)                   # Run `$ pip3 install "pandas[excel]" odfpy`.
4<DF>.to_sql('<table_name>', <connection>)      # Also `if_exists='fail/replace/append'`.

GroupBy

Object that groups together rows of a dataframe based on the value of the passed column.

1>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 6]], list('abc'), list('xyz'))
2>>> df.groupby('z').get_group(6)
3   x  y  z
4b  4  5  6
5c  7  8  6
1<GB> = <DF>.groupby(column_key/s)              # Splits DF into groups based on passed column.
2<DF> = <GB>.apply(<func>)                      # Maps each group. Func can return DF, Sr or el.
3<GB> = <GB>[column_key]                        # Single column GB. All operations return a Sr.
4<Sr> = <GB>.size()                             # A Sr of group sizes. Same keys as get_group().

GroupBy — Aggregate, Transform, Map:

1<DF> = <GB>.sum/max/mean/idxmax/all()          # Or: <GB>.agg(lambda <Sr>: <el>)
2<DF> = <GB>.rank/diff/cumsum/ffill()           # Or: <GB>.transform(lambda <Sr>: <Sr>)
3<DF> = <GB>.fillna(<el>)                       # Or: <GB>.transform(lambda <Sr>: <Sr>)
1>>> gb = df.groupby('z'); gb.apply(print)
2   x  y  z
3a  1  2  3
4   x  y  z
5b  4  5  6
6c  7  8  6
 1+-----------------+-------------+-------------+-------------+---------------+
 2|                 |    'sum'    |    'rank'   |   ['rank']  | {'x': 'rank'} |
 3+-----------------+-------------+-------------+-------------+---------------+
 4| gb.agg(…)       |      x   y  |             |      x    y |               |
 5|                 |  z          |      x  y   |   rank rank |        x      |
 6|                 |  3   1   2  |   a  1  1   | a    1    1 |     a  1      |
 7|                 |  6  11  13  |   b  1  1   | b    1    1 |     b  1      |
 8|                 |             |   c  2  2   | c    2    2 |     c  2      |
 9+-----------------+-------------+-------------+-------------+---------------+
10| gb.transform(…) |      x   y  |      x  y   |             |               |
11|                 |  a   1   2  |   a  1  1   |             |               |
12|                 |  b  11  13  |   b  1  1   |             |               |
13|                 |  c  11  13  |   c  2  2   |             |               |
14+-----------------+-------------+-------------+-------------+---------------+

Rolling

Object for rolling window calculations.

1<RSr/RDF/RGB> = <Sr/DF/GB>.rolling(win_size)   # Also: `min_periods=None, center=False`.
2<RSr/RDF/RGB> = <RDF/RGB>[column_key/s]        # Or: <RDF/RGB>.column_key
3<Sr/DF>       = <R>.mean/sum/max()             # Or: <R>.apply/agg(<agg_func/str>)

Plotly

1# $ pip3 install pandas plotly kaleido
2import pandas as pd, plotly.express as ex
3<Figure> = ex.line(<DF>, x=<col_name>, y=<col_name>)        # Or: ex.line(x=<list>, y=<list>)
4<Figure>.update_layout(margin=dict(t=0, r=0, b=0, l=0), )  # `paper_bgcolor='rgb(0, 0, 0)'`.
5<Figure>.write_html/json/image('<path>')                    # Also <Figure>.show().

Displays a line chart of total coronavirus deaths per million grouped by continent:

Covid Deaths

 1covid = pd.read_csv('https://raw.githubusercontent.com/owid/covid-19-data/8dde8ca49b'
 2                    '6e648c17dd420b2726ca0779402651/public/data/owid-covid-data.csv',
 3                    usecols=['iso_code', 'date', 'total_deaths', 'population'])
 4continents = pd.read_csv('https://gto76.github.io/python-cheatsheet/web/continents.csv',
 5                         usecols=['Three_Letter_Country_Code', 'Continent_Name'])
 6df = pd.merge(covid, continents, left_on='iso_code', right_on='Three_Letter_Country_Code')
 7df = df.groupby(['Continent_Name', 'date']).sum().reset_index()
 8df['Total Deaths per Million'] = df.total_deaths * 1e6 / df.population
 9df = df[df.date > '2020-03-14']
10df = df.rename({'date': 'Date', 'Continent_Name': 'Continent'}, axis='columns')
11ex.line(df, x='Date', y='Total Deaths per Million', color='Continent').show()

Displays a multi-axis line chart of total coronavirus cases and changes in prices of Bitcoin, Dow Jones and gold:

Covid Cases

 1import pandas as pd, plotly.graph_objects as go
 2
 3def main():
 4    covid, bitcoin, gold, dow = scrape_data()
 5    display_data(wrangle_data(covid, bitcoin, gold, dow))
 6
 7def scrape_data():
 8    def get_covid_cases():
 9        url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
10        df = pd.read_csv(url, usecols=['location', 'date', 'total_cases'])
11        return df[df.location == 'World'].set_index('date').total_cases
12    def get_ticker(symbol):
13        url = (f'https://query1.finance.yahoo.com/v7/finance/download/{symbol}?'
14               'period1=1579651200&period2=9999999999&interval=1d&events=history')
15        df = pd.read_csv(url, usecols=['Date', 'Close'])
16        return df.set_index('Date').Close
17    out = get_covid_cases(), get_ticker('BTC-USD'), get_ticker('GC=F'), get_ticker('^DJI')
18    return map(pd.Series.rename, out, ['Total Cases', 'Bitcoin', 'Gold', 'Dow Jones'])
19
20def wrangle_data(covid, bitcoin, gold, dow):
21    df = pd.concat([bitcoin, gold, dow], axis=1)  # Creates table by joining columns on dates.
22    df = df.sort_index().interpolate()            # Sorts table by date and interpolates NaN-s.
23    df = df.loc['2020-02-23':]                    # Discards rows before '2020-02-23'.
24    df = (df / df.iloc[0]) * 100                  # Calculates percentages relative to day 1.
25    df = df.join(covid)                           # Adds column with covid cases.
26    return df.sort_values(df.index[-1], axis=1)   # Sorts columns by last day's value.
27
28def display_data(df):
29    figure = go.Figure()
30    for col_name in reversed(df.columns):
31        yaxis = 'y1' if col_name == 'Total Cases' else 'y2'
32        trace = go.Scatter(x=df.index, y=df[col_name], name=col_name, yaxis=yaxis)
33        figure.add_trace(trace)
34    figure.update_layout(
35        yaxis1=dict(title='Total Cases', rangemode='tozero'),
36        yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'),
37        legend=dict(x=1.08),
38        width=944,
39        height=423
40    )
41    figure.show()
42
43if __name__ == '__main__':
44    main()

Appendix

Cython

Library that compiles Python code into C.

1# $ pip3 install cython
2import pyximport; pyximport.install()
3import <cython_script>
4<cython_script>.main()

Definitions:

  • All 'cdef' definitions are optional, but they contribute to the speed-up.
  • Script needs to be saved with a 'pyx' extension.
1cdef <ctype> <var_name> = <el>
2cdef <ctype>[n_elements] <var_name> = [<el>, <el>, ...]
3cdef <ctype/void> <func_name>(<ctype> <arg_name>): ...
1cdef class <class_name>:
2    cdef public <ctype> <attr_name>
3    def __init__(self, <ctype> <arg_name>):
4        self.<attr_name> = <arg_name>
1cdef enum <enum_name>: <member_name>, <member_name>, ...

Virtual Environments

System for installing libraries directly into project's directory.

1$ python3 -m venv <name>      # Creates virtual environment in current directory.
2$ source <name>/bin/activate  # Activates venv. On Windows run `<name>\Scripts\activate`.
3$ pip3 install <library>      # Installs the library into active environment.
4$ python3 <path>              # Runs the script in active environment. Also `./<path>`.
5$ deactivate                  # Deactivates the active virtual environment.

Basic Script Template

 1#!/usr/bin/env python3
 2#
 3# Usage: .py
 4#
 5
 6from sys import argv, exit
 7from collections import defaultdict, namedtuple
 8from dataclasses import make_dataclass
 9from enum import Enum
10import functools as ft, itertools as it, operator as op, re
11
12
13def main():
14    pass
15
16
17###
18##  UTIL
19#
20
21def read_file(filename):
22    with open(filename, encoding='utf-8') as file:
23        return file.readlines()
24
25
26if __name__ == '__main__':
27    main()