Comprehensive Python Cheatsheet ===============================. Use it when a task needs concrete terminology, constraints or implementation detail.
Python Cheat Sheet: Practical Language Reference
Snapshot 2026-08-04 16:17:00 UTC · version 1
Research document
Python Cheat Sheet: Practical Language Reference
Comprehensive Python Cheatsheet ===============================. Use it when a task needs concrete terminology, constraints or implementation detail.
Editorial note: curated source snapshot published by Collider.club under the MIT License. Source attribution is preserved in the front matter.
Source snapshot
Comprehensive Python Cheatsheet
Download text file, Fork me on GitHub or Check out FAQ.
Contents
1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
2. Data Types: Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
3. Syntax Rules: Function, Inline, Import, Decorator, Class, Duck_Type, Enum, Except.
4. System Calls: Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands.
5. Data Formats: JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.
6. Misc Topics: Operator, Match_Statement, Logging, Introspection, Threads, Asyncio.
7. Pip Packages: Progress_Bar, Plot, Table, Console_App, GUI, Scraping, Web, Profile.
8. Multimedia: NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly.
Main
if __name__ == '__main__': # Skips indented lines of code if file was imported.
main() # Executes user-defined `def main(): ...` function.
List
<list> = [<el>, <el>, ...] # Creates new list object. E.g. `list_a = [1, 2, 3]`.
<el> = <list>[index] # First index is 0, last -1. Also `<list>[i] = <el>`.
<list> = <list>[<slice>] # Also <list>[from_inclusive : to_exclusive : ±step].
<list>.append(<el>) # Appends element to the end. Or `<list> += [<el>]`.
<list>.extend(<coll>) # Appends collection's items. Or `<list> += <coll>`.
<list>.sort() # Sorts in ascending order. Accepts `reverse=True`.
<list>.reverse() # Reverses the order of elements. Takes linear time.
<list> = sorted(<coll>) # Returns a new sorted list. Accepts `reverse=True`.
<iter> = reversed(<list>) # Returns reversed iterator. Also list(<iterator>).
<el> = max(<coll>) # Returns the largest element. Also min(<el>, <el>).
<num> = sum(<coll>) # Returns a sum of elements. Also math.prod(<coll>).
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<coll>, key=lambda pair: pair[1])
sorted_by_both = sorted(<coll>, key=lambda p: (p[1], p[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
- For details about sort(), sorted(), max() and min() see Sortable.
- Module operator has function itemgetter() that can replace listed lambdas.
- This text uses the term collection instead of iterable. For rationale see duck types.
<int> = len(<list/dict/set/…>) # Returns number of items. Doesn't accept iterators.
<int> = <list>.count(<el>) # Counts occurrences. Also `if <el> in <coll>: ...`.
<int> = <list>.index(<el>) # Returns index of first occ. or raises ValueError.
<el> = <list>.pop() # Removes item from the end (or at index if passed).
<list>.insert(<int>, <el>) # Inserts item at index and shifts remaining items.
<list>.remove(<el>) # Removes the first occurrence or raises ValueError.
<list>.clear() # Removes all items. Also provided by dict and set.
Dictionary
<dict> = {key: val, key: val, ...} # Use `<dict>[key]` to get or assign the value.
<view> = <dict>.keys() # A collection of keys reflecting all changes.
<view> = <dict>.values() # A collection of values that reflects changes.
<view> = <dict>.items() # Coll. of tuples. Each contains key and value.
value = <dict>.get(key, default=None) # Returns 'default' argument if key is missing.
value = <dict>.setdefault(key, default) # Returns/writes 'default' when key is missing.
<dict> = collections.defaultdict(<type>) # Dict with automatic default value `<type>()`.
<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values)) # Creates key-value pairs from two collections.
<dict> = dict.fromkeys(keys [, value]) # Items get value None if only keys are passed.
<dict>.update(<dict>) # Adds items to dict. Passed dict has priority.
value = <dict>.pop(key) # Removes item or raises KeyError when missing.
{k for k, v in <dict>.items() if v == 123} # Returns a set of keys whose value equals 123.
{k: v for k, v in <dict>.items() if k in ks} # Returns a dict of items with specified keys.
Counter
>>> from collections import Counter
>>> counter = Counter(['blue', 'blue', 'red'])
>>> counter['yellow'] += 3
>>> print(counter.most_common())
[('yellow', 3), ('blue', 2), ('red', 1)]
Set
<set> = {<el>, <el>, ...} # Coll. of unique items. Also set(), set(<coll>).
<set>.add(<el>) # Adds item to the set. Same as `<set> |= {<el>}`.
<set>.update(<coll> [, ...]) # Adds items to the set. Same as `<set> |= <set>`.
<set> = <set>.union(<coll>) # Returns a set of all items. Also <set> | <set>.
<set> = <set>.intersection(<coll>) # Returns every shared item. Also <set> & <set>.
<set> = <set>.difference(<coll>) # Returns set's unique items. Also <set> - <set>.
<bool> = <set>.issuperset(<coll>) # Returns False when collection has unique items.
<bool> = <set>.issubset(<coll>) # Is collection a superset? Also <set> <= <set>.
<el> = <set>.pop() # Removes one of items. Raises KeyError if empty.
<set>.remove(<el>) # Removes the item or raises KeyError if missing.
<set>.discard(<el>) # Same as remove() but it doesn't raise an error.
Frozen Set
- Frozenset is immutable and hashable version of the normal set.
- That means it can be used as a key in a dict or as an item in a set.
<frozenset> = frozenset(<collection>)
Tuple
Tuple is an immutable and hashable list.
<tuple> = () # Returns an empty tuple. Also tuple(), tuple(<coll>).
<tuple> = (<el>,) # Returns tuple with one element. Or `<tup.> = <el>,`.
<tuple> = (<el>, <el> [, ...]) # Returns a tuple. Or `<tuple> = <el>, <el> [, ...]`.
Named Tuple
Tuple's subclass with named elements.
>>> import collections as co
>>> Point = co.namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
>>> print(p)
Point(x=1, y=2)
>>> p.x, p[1]
(1, 2)
Range
A sequence of evenly spaced integers.
<range> = range(stop) # I.e. range(to_exclusive). Ints from 0 to `stop-1`.
<range> = range(start, stop) # I.e. range(from, to_exc). From start to `stop-1`.
<range> = range(start, stop, step) # I.e. range(from_inclusive, to_exclusive, ±step).
>>> [i for i in range(3)]
[0, 1, 2]
Enumerate
Iterator that zips collection with range.
for i, el in enumerate(<coll>):
print(f'Element {el} has index {i}.')
Iterator
Potentially endless stream of elements.
import itertools as it
<iter> = iter(<coll>) # Iterator that returns passed elements one by one.
<iter> = iter(<func>, to_exc) # Calls `<func>()` until it receives 'to_exc' value.
<iter> = (<expr> for <name> in <coll>) # E.g. `(i+1 for i in range(3))`. Evaluates lazily.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
<list> = list(<iter>) # Returns a list of iterator's remaining elements.
<iter> = it.count(start=0, step=1) # Returns updated 'start' endlessly. Accepts floats.
<iter> = it.repeat(<obj> [, times]) # Returns passed element endlessly or 'times' times.
<iter> = it.cycle(<coll>) # Repeats the sequence endlessly. Accepts iterators.
<iter> = it.chain(<coll>, <coll>, ...) # Returns each element of each collection in order.
<iter> = it.chain.from_iterable(<coll>) # Accepts collection (i.e. iterable) of collections.
<iter> = it.islice(<coll>, stop) # Also accepts 'start' and 'step'. Args can be None.
<iter> = it.product(<coll>, <coll>) # Same as `((a, b) for a in arg_1 for b in arg_2)`.
- For loops call
'iter(<coll/iter>)', latter returning unmodified iterator.
Generator
- Any function that contains a yield statement returns a generator.
- Generators and iterators are interchangeable (see Iterator duck type).
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
Type
- All values in Python are objects.
- Every object has a certain type.
- Type and class are synonymous.
<type> = type(<obj>) # Object's type. Also `<obj>.__class__`.
<bool> = isinstance(<obj>, <type>) # Also `issubclass(type(<obj>), <type>)`.
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)
Some types do not have built-in names, so they must be imported:
from types import FunctionType, MethodType, LambdaType, GeneratorType
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. An ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods that class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().
>>> from collections.abc import Iterable, Collection, Sequence
>>> isinstance([1, 2, 3], Iterable)
True
+------------------+------------+------------+------------+
| | Iterable | Collection | Sequence |
+------------------+------------+------------+------------+
| list, range, str | yes | yes | yes |
| dict, set | yes | yes | |
| iter | yes | | |
+------------------+------------+------------+------------+
>>> from numbers import Number, Complex, Real, Rational, Integral
>>> isinstance(123, Number)
True
+--------------------+---------+---------+--------+----------+----------+
| | Number | Complex | Real | Rational | Integral |
+--------------------+---------+---------+--------+----------+----------+
| int | yes | yes | yes | yes | yes |
| fractions.Fraction | yes | yes | yes | yes | |
| float | yes | yes | yes | | |
| complex | yes | yes | | | |
| decimal.Decimal | yes | | | | |
+--------------------+---------+---------+--------+----------+----------+
String
Immutable sequence of characters.
<str> = 'abc' # Also "abc". Interprets \n, \t, \x00-\xff, etc.
<str> = <str>.strip() # Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split() # Splits it on one or more whitespace characters.
<list> = <str>.split(<str>) # Splits on passed string. Also `maxsplit=<int>`.
<list> = <str>.splitlines() # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_str>) # Joins items by using the string as a separator.
<bool> = <str> in <str> # Returns True if string contains the substring.
<bool> = <str>.startswith(<str>) # Pass tuple of strings to give multiple options.
<int> = <str>.find(<str>) # Returns start index of the first match or `-1`.
<str> = <str>.lower() # Lowers the case. Also upper/capitalize/title().
<str> = <str>.casefold() # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc.
<str> = <str>.replace(old, new) # Removes occurrences of string old if new is ''.
<str> = <str>.translate(table) # Get table via str.maketrans(<chr_to_str_dict>).
<str> = chr(<int>) # Converts passed integer into Unicode character.
<int> = ord(<str>) # Converts passed Unicode character into integer.
- Use
'unicodedata.normalize("NFC", <str>)'on strings like'Motörhead'before comparing them to other strings, because'ö'can be stored as one or two characters. 'NFC'converts such characters to a single character, while'NFD'converts them to two.
<bool> = <str>.isdecimal() # Checks all chars for [0-9]. Also [०-९], [٠-٩].
<bool> = <str>.isdigit() # Checks for [²³¹…] and isdecimal(). Also [፩-፱].
<bool> = <str>.isnumeric() # Checks for [¼½¾…] and isdigit(). Also [零〇一…].
<bool> = <str>.isalnum() # Checks for [ABC…] and isnumeric(). Also [ªµº…].
<bool> = <str>.isprintable() # Checks for [ !"#…], basic emojis and isalnum().
<bool> = <str>.isspace() # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…].
Regex
Functions for regular expression matching.
import re
<str> = re.sub(r'<regex>', new, text) # Substitutes occurrences with string 'new'.
<list> = re.findall(r'<regex>', text) # Returns all occurrences as string objects.
<list> = re.split(r'<regex>', text) # Add brackets around regex to keep matches.
<Match> = re.search(r'<regex>', text) # Returns first occ. of the pattern or None.
<Match> = re.match(r'<regex>', text) # Only searches at the start of the 'text'.
<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 the regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12).
- Argument
'new'can also be a function that accepts a Match object and returns a string. - Argument
'flags=re.IGNORECASE'can be used with all functions that are listed above. - Argument
'flags=re.MULTILINE'makes'^'and'$'match the start/end of each line. - Argument
'flags=re.DOTALL'makes'.'also accept the'\n'(besides all other chars). 're.compile(r"<regex>")'returns a Pattern object with methods sub(), findall(), etc.
Match Object
<str> = <Match>.group() # Returns the whole match. Also group(0).
<str> = <Match>.group(1) # Returns part inside the first brackets.
<tuple> = <Match>.groups() # Returns all bracketed parts as strings.
<int> = <Match>.start() # Returns start index of the whole match.
<int> = <Match>.end() # Returns the match's end index plus one.
Special Sequences
'\d' == '[0-9]' # Also [०-९…]. Matches decimal character.
'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches alphanumeric or _.
'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches whitespace.
- By default, decimal characters and alphanumerics from all alphabets are matched unless
'flags=re.ASCII'is used. It restricts special sequence matches to the first 128 Unicode characters and also prevents'\s'from accepting'\x1c','\x1d','\x1e'and'\x1f'(non-printable characters that divide text into files, tables, rows and fields, respectively). - Use a capital letter, i.e.
'\D','\W'or'\S', for negation. All non-ASCII characters are matched if ASCII flag is used in conjunction with a capital letter.
Format
String formatting mechanisms.
<str> = f'{<obj>}, {<obj>}' # Braces can also contain expressions.
<str> = '{}, {}'.format(<obj>, <obj>) # Or '{0}, {a}'.format(<obj>, a=<obj>).
<str> = '%s, %s' % (<obj>, <obj>) # Old and redundant formatting method.
Example
>>> Person = collections.namedtuple('Person', 'name height')
>>> jean = Person('Jean-Luc', 187)
>>> f'{jean.name} is {jean.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'
Options
{<obj>:<10} # '<obj> '.
{<obj>:^10} # ' <obj> '.
{<obj>:>10} # ' <obj>'.
{<obj>:.<10} # '<obj>.....'.
{<obj>:0} # '<obj>'.
- Objects are converted to strings with format() function, e.g.
'format(<obj>, "<10")'. - Options can be generated dynamically via nested braces:
f'{<obj>:{<str/int>}[…]}'. - Adding
'='to the expression prepends it to its result, e.g.f'{1+1=}'returns'1+1=2'. - Adding
'!r'to the expression first calls result's repr() method and only then format().
Strings
{'abcde':10} # 'abcde '.
{'abcde':10.3} # 'abc '.
{'abcde':.3} # 'abc'.
{'abcde'!r:10} # "'abcde' ".
Numbers
{123456:10} # ' 123456'.
{123456:10,} # ' 123,456'.
{123456:10_} # ' 123_456'.
{123456:+10} # ' +123456'.
{123456:=+10} # '+ 123456'.
Floats
{1.23456:10.3} # ' 1.23'.
{1.23456:10.3f} # ' 1.235'.
{1.23456:10.3e} # ' 1.235e+00'.
{1.23456:10.3%} # ' 123.456%'.
Comparison of presentation types:
+---------------+---------------+---------------+---------------+---------------+
| | {<number>} | {<num>:f} | {<num>:e} | {<num>:%} |
+---------------+---------------+---------------+---------------+---------------+
| 0.000056789 | 5.6789e-05 | 0.000057 | 5.678900e-05 | 0.005679% |
| 0.00056789 | 0.00056789 | 0.000568 | 5.678900e-04 | 0.056789% |
| 0.0056789 | 0.0056789 | 0.005679 | 5.678900e-03 | 0.567890% |
| 0.056789 | 0.056789 | 0.056789 | 5.678900e-02 | 5.678900% |
| 0.56789 | 0.56789 | 0.567890 | 5.678900e-01 | 56.789000% |
| 5.6789 | 5.6789 | 5.678900 | 5.678900e+00 | 567.890000% |
| 56.789 | 56.789 | 56.789000 | 5.678900e+01 | 5678.900000% |
+---------------+---------------+---------------+---------------+---------------+
+---------------+---------------+---------------+---------------+---------------+
| | {<float>:.2} | {<num>:.2f} | {<num>:.2e} | {<num>:.2%} |
+---------------+---------------+---------------+---------------+---------------+
| 0.000056789 | 5.7e-05 | 0.00 | 5.68e-05 | 0.01% |
| 0.00056789 | 0.00057 | 0.00 | 5.68e-04 | 0.06% |
| 0.0056789 | 0.0057 | 0.01 | 5.68e-03 | 0.57% |
| 0.056789 | 0.057 | 0.06 | 5.68e-02 | 5.68% |
| 0.56789 | 0.57 | 0.57 | 5.68e-01 | 56.79% |
| 5.6789 | 5.7 | 5.68 | 5.68e+00 | 567.89% |
| 56.789 | 5.7e+01 | 56.79 | 5.68e+01 | 5678.90% |
+---------------+---------------+---------------+---------------+---------------+
'{<num>:g}'is'{<float>:.6}'that strips'.0'and has 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. Hence
'{6.5:.0f}'becomes a'6', while'{7.5:.0f}'an'8'. - The last rule only effects numbers that can be represented exactly by a float (
.5,.25, …).
Ints
{90:x} # Converts 90 to hexadecimal number '5a'.
{90:b} # Converts 90 to binary number '1011010'.
{90:c} # Converts 90 to Unicode character 'Z'.
Numbers
<integer> = int(<float/str/bool>) # A whole number. Truncates floats.
<float> = float(<integer/str/bool>) # 8-byte decimal. Also <fl>e±<int>.
<complex> = complex(real=0, imag=0) # Complex number. Also <fl> ± <fl>j.
<Fract> = fractions.Fraction(numr, denom) # `<Fraction> = <Fraction> / <int>`.
<Decimal> = decimal.Decimal(<str/int/tup>) # `Decimal((1, (2,), 3)) == -2000`.
'int(<str>)'and'float(<str>)'raise ValueError exception if string is malformed.- Decimal objects store numbers exactly, unlike most floats where
'1.1 + 2.2 != 3.3'. - Floats can be compared with:
'math.isclose(<float>, <float>, rel_tol=1e-9)'. - Precision of decimal operations is set with:
'decimal.getcontext().prec = <int>'. - Bools can be used anywhere ints can, since bool is a subclass of int:
'True + 1 == 2'.
Built-in
<num> = abs(<num>) # E.g. `abs(-50) == abs(50) == 50`.
<num> = pow(<num>, <num>) # E.g. `pow(3, 4) == 3 ** 4 == 81`.
<num> = round(<num> [, ndigits]) # E.g. `round(123.45, -1) == 120`.
<num> = min(<coll_of_nums>) # Also `max(<num>, <num> [, ...])`.
<num> = sum(<coll_of_nums>) # Also `math.prod(<coll_of_nums>)`.
Math
import math as mt
<num> = mt.pi/inf/nan # `inf*0` and `nan+1` return `nan`.
<num> = mt.sqrt/factorial(<num>) # `sqrt(-1)` will raise ValueError.
<num> = mt.sin/cos/tan(<num>) # Also degrees, radians, asin, etc.
<num> = mt.log/log10/log2(<num>) # Log() can accept 'base' argument.
Statistics
import statistics as st
<obj> = st.mean/median(<coll>) # Mode returns most common element.
<num> = st.variance/stdev(<coll>) # Estimates values from the sample.
<list> = st.quantiles(<coll>, n=4) # Estimates cut points from sample.
Random
import random as rd
<num> = rd.random() # Selects random float from [0, 1).
<num> = rd.randint/uniform(a, b) # Selects an int/float from [a, b].
<num> = rd.gauss(mean, stdev) # Also triangular(low, high, mode).
<obj> = rd.choice(<sequence>) # Doesn't mutate. Also sample(p, n).
rd.shuffle(<list>) # Works with all mutable sequences.
Hex, Bin
<int> = 0x<hex> # E.g. `0xFf == 255`. Also 0b<bin>.
<int> = int('±<hex>', 16) # Also int('±0x<hex>/±0b<bin>', 0).
<str> = hex(<int>) # Returns '[-]0x<hex>'. Also bin().
Bitwise
<int> = <int> & <int> # E.g. `0b1100 & 0b1010 == 0b1000`.
<int> = <int> | <int> # E.g. `0b1100 | 0b1010 == 0b1110`.
<int> = <int> ^ <int> # E.g. `0b1100 ^ 0b1010 == 0b0110`.
<int> = <int> << n_bits # E.g. `0b1111 << 4 == 0b11110000`.
<int> = ~<int> # E.g. `~100 == -(100+1) == -101`.
Combinatorics
import itertools as it
>>> list(it.product('abc', repeat=2)) # a b c
[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x
('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x
('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x
>>> list(it.permutations('abc', 2)) # a b c
[('a', 'b'), ('a', 'c'), # a . x x
('b', 'a'), ('b', 'c'), # b x . x
('c', 'a'), ('c', 'b')] # c x x .
>>> list(it.combinations('abc', 2)) # a b c
[('a', 'b'), ('a', 'c'), # a . x x
('b', 'c') # b . . x
] # c . . .
Datetime
Module that provides date, time and datetime objects.
# $ pip3 install python-dateutil
from datetime import *
import zoneinfo, dateutil.tz
<D> = date(year, month, day) # Only accepts valid dates between AD 1 and 9999.
<T> = time(hour=0, minute=0, second=0) # Accepts `microsecond=0, tzinfo=None, fold=0`.
<DT> = datetime(year, month, day, hour=0) # Accepts `minute=0, second=0, microsecond=0, …`.
<TD> = timedelta(weeks=0, days=0, hours=0) # Accepts `minutes=0, seconds=0, microseconds=0`.
- Times and datetimes that have defined timezone are called aware and ones that don't, naive. If time or datetime 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 (usually for one hour).- Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns
'[±D, ]H:MM:SS[.…]'and total_seconds() a float of seconds. - Use
'<D/DT>.weekday()'to get the day of the week as an int, with Monday being 0.
Now
<D/DTn> = D/DT.today() # Current local date or naive DT. Also DT.now().
<DTa> = DT.now(<tzinfo>) # Aware DT from current time in passed timezone.
- To extract time use
'<DTn>.time()','<DTa>.time()'or'<DTa>.timetz()'.
Timezone
<tzinfo> = timezone.utc # Coordinated universal time. London without DST.
<tzinfo> = timezone(<timedelta>) # Timezone with fixed offset from universal time.
<tzinfo> = dateutil.tz.tzlocal() # Local timezone with dynamic offset from the UTC.
<tzinfo> = zoneinfo.ZoneInfo('<iana_key>') # 'Continent/City_Name' zone with dynamic offset.
<DTa> = <DT>.astimezone(<tzinfo>) # Converts to the passed or local fixed timezone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Changes the timezone object without conversion.
- Timezones returned by tzlocal(), ZoneInfo(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.
- To get ZoneInfo() to work on Windows run
'> pip3 install tzdata'.
Encode
<D/T/DT> = D/T/DT.fromisoformat(<str>) # Object from the ISO string. Raises ValueError.
<DT> = DT.strptime(<str>, '<format>') # Naive or aware datetime from the custom string.
<D/DTn> = D/DT.fromordinal(<int>) # Date or DT from days since the Gregorian NYE 1.
<DTn> = DT.fromtimestamp(<float>) # A local naive DT from seconds since the epoch.
<DTa> = DT.fromtimestamp(<float>, <tz>) # An 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
<str> = <D/T/DT>.isoformat(sep='T') # Also `timespec='auto/hours/minutes/seconds/…'`.
<str> = <D/T/DT>.strftime('<format>') # Returns custom string representation of object.
<int> = <D/DT>.toordinal() # Days since NYE 1, ignoring DT's time and zone.
<float> = <DTn>.timestamp() # Seconds since the epoch from a local naive DT.
<float> = <DTa>.timestamp() # Seconds since the epoch from an aware datetime.
Format
>>> dta = datetime.strptime('2025-08-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
>>> dta.strftime("%dth of %B '%y (%a), %I:%M %p %Z")
"14th of August '25 (Thu), 11:39 PM UTC+02:00"
'%z'accepts'±HH[:]MM'and returns'±HHMM'or empty string if object is naive.'%Z'accepts'UTC','GMT'or local timezone's code and returns timezone's name,'UTC[±HH:MM]'if timezone is nameless, or an empty string if object is naive.
Arithmetics
<bool> = <D/DTn> > <D/DTn> # Ignores time jumps (fold attribute). Also `==`.
<bool> = <DTa> > <DTa> # Ignores time jumps if they share tzinfo object.
<TD> = <D/DTn> - <D/DTn> # Ignores jumps. Convert to UTC for actual delta.
<TD> = <DTa> - <DTa> # Ignores jumps if they share the tzinfo object.
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into a missing hour.
<TD> = <TD> ± <TD> # Also `<TD> = abs(<TD>)`, `<num> = <TD> / <TD>`.
Function
Independent block of code that returns a value when called.
def my_func(<nondefault_args>): ... # E.g. `my_func(x, y):`.
def my_func(<default_args>): ... # E.g. `my_func(x=0, y=0):`.
def my_func(<nondef_args>, <def_args>): ... # E.g. `my_func(x, y=0):`.
- Function returns None if it doesn't encounter the
'return <object/expr>'statement. - Run
'global <var_name>'inside the function before assigning to the global variable. - Value of a default argument is evaluated when function is first encountered in the scope.
- Any mutation of a default argument value will persist between function invocations!
Function Call
<obj> = <func>(<positional_args>) # E.g. `my_func(0, 0)`.
<obj> = <func>(<keyword_args>) # E.g. `my_func(x=0, y=0)`.
<obj> = <func>(<pos_args>, <key_args>) # E.g. `my_func(0, y=0)`.
Splat
Splat operator, i.e. '*', expands collection into positional arguments, while splatty-splat, i.e. '**', expands a dictionary into keyword arguments.
args, kwargs = (1, 2), {'z': 3}
func(*args, **kwargs)
Is the same as:
func(1, 2, z=3)
Inside Function Def
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
def add(*args):
return sum(args)
>>> add(1, 2, 3)
6
+-------------------------+--------------+--------------+------------+
| | fn(x=1, y=2) | fn(1, y=2) | fn(1, 2) |
+-------------------------+--------------+--------------+------------+
| fn(x, *args, **kwargs): | yes | yes | yes |
| fn(*args, y, **kwargs): | yes | yes | |
| fn(*, x, **kwargs): | yes | | |
+-------------------------+--------------+--------------+------------+
Collection Unpacking
head, *body, tail = <collection> # Head or tail can be omitted.
Inside Coll Literals
<list> = [*<coll> [, ...]] # Same as `list(<coll>) [+ ...]`.
<tuple> = (*<coll>, [...]) # Same as `tuple(<coll>) [+ ...]`.
<set> = {*<coll> [, ...]} # Same as `set(<coll>) [| ...]`.
<dict> = {**<dict> [, ...]} # Last dict has priority. Also |.
Inline
Lambda
<func> = lambda: <return_val> # A single statement function.
<func> = lambda <arg> [, ...]: <return_val> # Also allows default arguments.
Comprehensions
<list> = [i+1 for i in range(5)] # Returns `[1, 2, 3, 4, 5]`.
<iter> = (i for i in range(10) if i > 5) # Returns `iter([6, 7, 8, 9])`.
<set> = {i+5 for i in range(5)} # Returns `{5, 6, 7, 8, 9}`.
<dict> = {i: i**2 for i in range(1, 4)} # Returns `{1: 1, 2: 4, 3: 9}`.
>>> [l+r for l in 'abc' for r in '123'] # Inner loop is on right side.
['a1', 'a2', 'a3', ..., 'c3']
Map, Filter, Reduce
from functools import reduce
<iter> = map(lambda x: x + 1, range(5)) # Returns `iter([1, 2, 3, 4, 5])`.
<iter> = filter(lambda x: x > 5, range(10)) # Returns `iter([6, 7, 8, 9])`.
<obj> = reduce(lambda out, x: out+x, range(5)) # Returns 10. Accepts 'initial'.
Any, All
<bool> = any(<collection>) # Is bool(<el>) True for any el?
<bool> = all(<collection>) # Is it True for all (or empty)?
Conditional Exp
<obj> = <exp> if <condition> else <exp> # Evaluates only one expression.
>>> [i if i else 'zero' for i in (0, 1, 2)] # `any(['', [], None])` is False.
['zero', 1, 2]
And, Or
<obj> = <exp> and <exp> [and ...] # Returns first false or last obj.
<obj> = <exp> or <exp> [or ...] # Returns first true or last obj.
Walrus Operator
>>> [i for ch in '0123' if (i := int(ch))] # Assigns to var in mid-sentence.
[1, 2, 3]
Named Tuple, Enum, Dataclass
from collections import namedtuple
Point = namedtuple('Point', 'x y') # Creates tuple's subclass.
point = Point(0, 0) # Returns its instance.
from enum import Enum
Direction = Enum('Direction', 'N E S W') # Creates an enumeration.
direction = Direction.N # Returns its member.
from dataclasses import make_dataclass
Player = make_dataclass('Player', ['p', 'd']) # Creates a normal class.
player = Player(point, direction) # Returns its instance.
Import
Mechanism that makes code in one file available to another file.
import <module> # Imports a built-in module or `<module>.py`.
import <package> # Built-in package or `<package>/__init__.py`.
import <package>.<module> # Package's module or `<package>/<module>.py`.
from <pkg/mod>[.…] import <obj> # Imports a module, class, func or variable.
- Package is a collection of modules, but it can also define its own functions, variables, etc. On a filesystem this corresponds to a directory of Python files with an optional init script.
'import <package>'only exposes modules that are imported inside'__init__.py'.- Directory of the file that is passed to python command serves as the root of local imports.
- Use relative imports, i.e.
'from .[…][<pkg/mod>[.…]] import <obj>', if project has scattered entry points. Another option is to install the whole project by moving its code into 'src' dir, adding 'pyproject.toml' to its root, and running'$ pip3 install -e .'.
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 its nested function (any value that is referenced from within multiple nested functions gets shared).
def get_multiplier(a):
def out(b):
return a * b
return out
>>> mul_by_3 = get_multiplier(3)
>>> mul_by_3(10)
30
Partial
Partial transforms a function by storing some (or all) of its arguments. It is useful when a function needs to be passed as an argument, e.g. 'collections.defaultdict(<func>)', 'iter(<func>, to_exc)' and 'dataclasses.field(default_factory=<func>)'.
def mul(a, b):
return a * b
>>> import functools as ft
>>> mul_by_3 = ft.partial(mul, 3)
>>> mul_by_3(10)
30
Non-Local
If variable is being assigned to anywhere in the scope (i.e., body of a function), it is treated as a local variable unless it is declared 'global' or 'nonlocal' before its first usage.
def get_counter():
i = 0
def out():
nonlocal i
i += 1
return i
return out
>>> counter = get_counter()
>>> counter(), counter(), counter()
(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.
@decorator_name
def func_that_is_passed_to_dec():
...
Debugger
Prints function's name every time function is called. It uses '@wraps' decorator to move the metadata from func() into out(). Without it, 'add.__name__' would return 'out'.
from functools import wraps
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out
@debug
def add(x, y):
return x + y
Cache
Stores function's return values and reuses them later. To clear stored return values run '<func>.cache_clear()', or use '@lru_cache(maxsize=<int>)' decorator instead.
from functools import cache
@cache
def fibonacci(n):
return n if n < 2 else fibonacci(n-2) + fibonacci(n-1)
- CPython interpreter limits recursion depth to 3000 by default.
- To increase this limit run
'sys.setrecursionlimit(<int>)'.
Debug with Args
Decorator that prints function's name and optionally also it's result.
from functools import wraps
def debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
res = func(*args, **kwargs)
if print_result:
print(res)
return res
return out
return decorator
@debug(print_result=True)
def add(x, y):
return x + y
- Using
'@debug'without arguments won't work here because add() is then passed via 'print_result' argument. To fix this issue use'def debug(fn=None, *, ...)'in def and'return decorator(fn) if fn else decorator'as the last line.
Class
A template for creating user-defined objects.
class MyClass:
def __init__(self, a):
self.a = a
def __str__(self):
return str(self.a)
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
@classmethod
def get_class_name(cls):
return cls.__name__
>>> obj = MyClass(1)
>>> obj.a, str(obj), repr(obj)
(1, '1', 'MyClass(1)')
- Methods whose names start and end with two underscores are called special methods.
- They are executed when object is passed to a built-in function or used as an operand. For example,
'print(a)'calls'a.__str__()'and'a + b'calls'a.__add__(b)'. - See module operator to get names of all special methods that are called by operators.
- Methods that are decorated with
'@staticmethod'receive neither 'self' nor 'cls' arg. - Return value of str() special method should be readable and of repr() unambiguous.
All calls to str() special method are dispatched to repr() when only repr() is provided.
Expressions that call str() special method:
f'{obj}'
str(obj)
print(obj)
Expressions that call repr() special method:
f'{obj!r}'
str/repr/print([obj])
str/repr/print({obj: obj})
str/repr/print(MyDataClass(obj))
Subclass
- Inheritance is a mechanism that enables a class to extend some other class (i.e. subclass to extend its parent) and by doing so inherit all of its methods and attributes.
- Subclass can then add its own methods and attributes or override inherited ones by reusing their names.
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'Person({self.name!r})'
def __lt__(self, other):
return self.name < other.name
class Employee(Person):
def __init__(self, name, staff_num):
super().__init__(name)
self.staff_num = staff_num
def __repr__(self):
return f'Employee({self.name!r}, {self.staff_num})'
>>> people = [Person('Bob'), Employee('Ann', 0)]
>>> sorted(people)
[Employee('Ann', 0), Person('Bob')]
Type Annotations
They are used by type checkers like mypy and Pydantic, however they are not enforced by CPython interpreter. To annotate a function use 'def f(a: int = 0) -> int: ...'.
from collections.abc import *
<name>: <type> [| ...] [= <obj>]
<name>: list/set/Iterable/Sequence[<type>] [= <obj>]
<name>: tuple/dict[<type>, ...] [= <obj>]
Dataclass
It uses class variables to generate init(), repr() and eq() special methods.
import dataclasses as dc
@dc.dataclass(order=False, frozen=False)
class MyClass:
<attr_name>: <type>
<attr_name>: <type> = <obj>
<attr_name>: list = dc.field(default_factory=list)
- 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 accepts any callable object. - For attributes and arguments of arbitrary type use
'<attr_name>: typing.Any'.
Inline:
P = dc.make_dataclass('P', ['x', 'y'])
P = dc.make_dataclass('P', [('x', float), ('y', float)])
P = dc.make_dataclass('P', [('x', float, 0), ('y', float, 0)])
Property
Pythonic way of implementing getters and setters.
class Person:
@property
def name(self):
return ' '.join(self._name)
@name.setter
def name(self, value):
self._name = value.split()
>>> person = Person()
>>> person.name = '\t Guido van Rossum \n'
>>> person.name
'Guido van Rossum'
Slots
Mechanism restricting objects to listed attributes.
class Point:
__slots__ = ('x', 'y')
Copy
from copy import copy, deepcopy
<object> = copy/deepcopy(<object>)
Duck Types
A duck type is an implicit type that prescribes a set of special methods. Any object that possesses all of the duck type's prescribed methods 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 user-defined objects compare not equal by default (because id() returns object's memory address that is guaranteed to be unique). - Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. Result is False if both return NotImplemented.
- Method ne() (called by
'!=') automatically works on any object that has eq() defined.
class MyComparable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
Hashable
- Hashable object needs hash() and eq() methods and its hash value must 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 the eq() method.
class MyHashable:
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __hash__(self):
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 (called by <, >, <=, >=) and the rest will be automatically generated.
- Built-in functions sorted() and min() only require lt() method, while max() only requires gt(). However, it's best to define them all so that confusion doesn't arise in other context.
- When two lists, strings, or data classes are compared, their values get compared one by one 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 their values being equal.
- To sort collection of strings in proper alphabetical order pass
'key=locale.strxfrm'to sorted() after running'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'.
from functools import total_ordering
@total_ordering
class MySortable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __lt__(self, other):
if isinstance(other, type(self)):
return self.a < other.a
return NotImplemented
Iterator
- Any object that has special methods next() and iter() is an iterator.
- Next() should return the next item or raise StopIteration exception.
- Iter() should return an unmodified iterator, i.e. the 'self' argument.
- Any object that has iter() special method can be used in a for loop.
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
>>> counter = Counter()
>>> next(counter), next(counter), next(counter)
(1, 2, 3)
Python has many different iterator objects:
- Sequence iterators returned by the iter() function, such as 'list_iterator'.
- Objects returned by the itertools module, such as count, repeat and cycle.
- Generator objects returned by the generator functions and expressions.
- File objects returned by the open() function, SQLite cursor objects, etc.
Callable
- All functions and classes have a call() method that is executed when they are called.
- Use
'callable(<obj>)'or'isinstance(<obj>, collections.abc.Callable)'to check if object is callable and'inspect.signature(<obj>)'for info about args. - When this text uses
'<function>'as an argument, it actually means'<callable>'.
class Counter:
def __init__(self):
self.i = 0
def __call__(self, step):
self.i += step
return self.i
>>> counter = Counter()
>>> counter(1), counter(1), counter(1)
(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 (file, socket, etc.).
- Exit() should release the resources (for example close the file, release the lock, etc.).
- Any exception that happens inside the with block is passed to exit() method. Exit() can then suppress this exception by returning a true value (not None, False, 0, etc.).
class MyOpen:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exception, traceback):
self.file.close()
>>> with open('test.txt', 'w') as file:
... file.write('Hello World!')
>>> with MyOpen('test.txt') as file:
... print(file.read())
Hello World!
Iterable Duck Types
Iterable
- Only required special method is iter(). It should return an iterator of object's items.
- Special method contains() automatically works on any object that has iter() defined.
class MyIterable:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
>>> obj = MyIterable([1, 2, 3])
>>> [el for el in obj]
[1, 2, 3]
>>> 1 in obj
True
Collection
- Only required methods are iter() and len(). Len() should return the length of collection.
- This text refers to all iterable objects as collections, which is technically incorrect. The term iterable was avoided because it sounds scarier and more vague than collection. The main drawback of this decision is that the reader could think a certain function doesn't accept iterators when it actually does, since iterators are the only built-in objects that are iterable but are not collections.
class MyCollection:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
Sequence
- Only required methods are len() and getitem(). Getitem() should return an item at the passed index or raise IndexError (it may also support negative indices and/or slices).
- Iter() and contains() automatically work on any object with defined getitem() method.
- Reversed() automatically works on any object that has len() and getitem() defined. It returns reversed iterator of object's items.
class MySequence:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
def __reversed__(self):
return reversed(self.a)
Discrepancies between glossary definitions and abstract base classes:
- Python's glossary defines iterable as any object with special methods iter() or getitem(), and sequence as any object with getitem() and len(). It doesn't define the term collection.
- Using ABC Iterable with isinstance() or issubclass() only checks whether object/class has special method iter(), while ABC Collection checks for iter(), contains() and len().
ABC Sequence
- It's a richer interface than the basic sequence that also requires just len() and getitem().
- Extending it generates iter(), contains(), reversed(), index() and count() special methods.
- Unlike
'abc.Iterable'and'abc.Collection', it is not a duck type. That is why exp.'issubclass(MySequence, abc.Sequence)'would return False even if MySequence had all methods defined. It however recognizes list, tuple, range, string, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.
from collections import abc
class MyAbcSequence(abc.Sequence):
def __init__(self, a):
self.a = a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
Required and automatically available methods:
+--------------+------------+------------+------------+--------------+
| | Iterable | Collection | Sequence | abc.Sequence |
+--------------+------------+------------+------------+--------------+
| __iter__ | REQ | REQ | Yes | Yes |
| __contains__ | Yes | Yes | Yes | Yes |
| __len__ | | REQ | REQ | REQ |
| __getitem__ | | | REQ | REQ |
| __reversed__ | | | Yes | Yes |
| index | | | | Yes |
| count | | | | Yes |
+--------------+------------+------------+------------+--------------+
- Method iter() is required for
'isinstance(<obj>, abc.Iterable)'to return True, however any object with getitem() method works with any code expecting an iterable. - MutableSequence, Set, MutableSet, Mapping and MutableMapping ABCs are also extendable. Use
'<abc>.__abstractmethods__'to get names of required methods.
Enum
Class of named constants called members.
from enum import Enum, auto
class MyEnum(Enum):
<member_name> = auto() # An increment of last numeric value or 1.
<member_name> = <value> # Values don't have to be hashable/unique.
<member_name> = <el>, <el>, ... # Value can be a collection, e.g. a tuple.
- Methods receive the member they were called on as the 'self' argument.
- Accessing a member named after a reserved keyword raises SyntaxError.
<memb> = <enum>.<member_name> # Accesses a member via enum's attribute.
<memb> = <enum>['<member_name>'] # Returns the member or raises KeyError.
<memb> = <enum>(<value>) # Returns the member or raises ValueError.
<str> = <member>.name # Returns the member's name as a string.
<obj> = <member>.value # Value can't be a user-defined function.
<list> = list(<enum>) # Returns a list containing every member.
<list> = <enum>._member_names_ # Returns a list containing member names.
<list> = [m.value for m in <enum>] # Returns a list containing member values.
<enum> = type(<member>) # Returns an enum. Also <memb>.__class__.
<iter> = itertools.cycle(<enum>) # Returns an endless iterator of members.
<memb> = random.choice(list(<enum>)) # Randomly selects one of enum's members.
Inline
Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON')
Cutlery = Enum('Cutlery', ['FORK', 'KNIFE', 'SPOON'])
Cutlery = Enum('Cutlery', {'FORK': 1, 'KNIFE': 2, 'SPOON': 3})
User-defined functions cannot be values, so they must be wrapped:
import functools as ft
and_ = ft.partial(lambda l, r: l and r)
or_ = ft.partial(lambda l, r: l or r)
LogicOp = Enum('LogicOp', {'AND': and_, 'OR': or_})
Exceptions
try:
<code>
except <exception>:
<code>
Full Try Statement
try:
<code_1>
except <exception_a>:
<code_2_a>
except <exception_b>:
<code_2_b>
else:
<code_2_c>
finally:
<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 the function block delimits scope).
- To catch signals use
'signal.signal(signal_number, my_handler_function)'.
Catching Exceptions
except <exception>: ...
except <exception> as <name>: ...
except (<exception>, ...) [as <name>]: ...
- Except clause catches all subclasses, e.g.
'OSError'is caught by'except Exception:'. - Use
'traceback.print_exc()'to print the full error message to standard error stream. - Use
'print(<name>)'to print just the cause of the exception (its arguments) to stdout. - Use
'logging.exception(<str>)'to log the passed message followed by the full error message of the caught exception. For details about how to set up the logger see Logging. 'sys.exc_info()'returns type, object and traceback of the caught exception as a tuple.
Raising Exceptions
raise <exception>
raise <exception>()
raise <exception>(<obj> [, ...])
Re-raising caught exception:
except <exception> [as <name>]:
...
raise
Exception Object
arguments = <name>.args
exc_type = <name>.__class__
filename = <name>.__traceback__.tb_frame.f_code.co_filename
func_name = <name>.__traceback__.tb_frame.f_code.co_name
line_str = linecache.getline(filename, <name>.__traceback__.tb_lineno)
trace_str = ''.join(traceback.format_tb(<name>.__traceback__))
error_msg = ''.join(traceback.format_exception(*sys.exc_info()))
Built-in Exceptions
BaseException
+- SystemExit # Raised when `sys.exit()` is called. See #Exit for details.
+- KeyboardInterrupt # Raised when the user hits the interrupt key, i.e. `ctrl-c`.
+- Exception # User-defined exceptions should be derived from this class.
+- ArithmeticError # Base class for arithmetic errors such as ZeroDivisionError.
+- AssertionError # Raised by `assert <exp>` if expression returns false value.
+- AttributeError # Raised when object doesn't have requested attribute/method.
+- EOFError # Raised by `input()` when it hits an end-of-file condition.
This HTML preview is truncated for page performance. The canonical Markdown file contains the complete snapshot.
Why MDRSS assigned this score
- evidence comes from multiple domains
- some evidence URLs look like primary-source hosts
Evidence (4)
concept:programming-runtimeorg:collider-club Discussion 0
Sign in to join the discussion.