0% found this document useful (0 votes)
26 views

best-python-cheat-sheet

The document is a comprehensive Python cheat sheet covering various topics such as built-in functions, flow control, data structures, and operators. It includes syntax examples, explanations of keywords, and details on scope and context management. The cheat sheet serves as a quick reference guide for Python programming concepts and functionalities.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

best-python-cheat-sheet

The document is a comprehensive Python cheat sheet covering various topics such as built-in functions, flow control, data structures, and operators. It includes syntax examples, explanations of keywords, and details on scope and context management. The cheat sheet serves as a quick reference guide for Python programming concepts and functionalities.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

The *Best Python Cheat Sheet

Just what you need


Built-in (1) Execution (26) List (9) Set (10)
Bytes (10) Flow control (4) Number (22) String (17)
Class (12) Function (11) Operator (3) Test (26)
Debug (26) Generator (17) Regex (20) Time (23)
Decorator (14) Iterator (16) Resource (26) Tuple (8)
Dictionary (9) Keyword (1) Scope (6) Types (26)
Exception (24) Library (26) Sequence (7)

Keyword
and continue for match 1 True
as def from None try
assert del global nonlocal type 1
async elif if not while
await else import or with
break except in pass yield
case 1 False is raise _1
class finally lambda return
1
Soft keywords

Built-in
Built-in functions
abs(number) Absolute value of bytes(…) New bytes object
number from byte-integers,
string, or bytes
aiter(async_iterable Asynchronous
) iterator for an callable(object) True if object is
asynchronous callable
iterable
chr(i) One character string
all(iterable) True if all elements for unicode ordinal
of iterable are true i (0 <= i <=
(all([]) is True) 0x10ffff)
any(iterable) True if any element classmethod(func) Transform function
of iterable is true into class method
(any([]) is False)
compile(source, …) Compile source into
ascii(object) Return repr(object) code or AST object
with non-ASCII
complex(real=0, Complex number with
characters escaped
imag=0) the value real +
bin(number) Convert number to imag*1j
binary string
delattr(object, Delete the named
bool(object) Boolean value of name) attribute, if object
object, see __bool__ allows
breakpoint(*args, Drop into debugger dict(…) Create new
**kwds) by calling dictionary
sys.breakpointhook(*
dir([object]) List of names in the
args, **kwds)
local scope, or
bytearray(…) New array of bytes object.__dir__() or
from byte-integers, attributes
string, bytes, or
divmod(x, y) Return (quotient
object with buffer
x//y, remainder x%y)
API

© kieranholland.com 1 of 26
The *Best Python Cheat Sheet

enumerate(iterable, Enumerate object as iter(object, …) Iterator for object


start=0) (n, item) pairs with
len(object) Length of object
n initialised to
start value list(…) Create list
eval(source, Execute Python locals() Dictionary of
globals=None, expression string, current local symbol
locals=None) or code object from table
compile() map(func, Apply function to
exec(source, Execute Python *iterables) every item of
globals=None, statements string, iterable(s)
locals=None) or code object from max(…, key=func) Largest item of
compile() iterable or
filter(func, Iterator yielding arguments,
iterable) items where optionally comparing
bool(func(item)) is value of func(item)
True, or bool(item) memoryview(object) Access internal
if func is None object data via
float(x=0) Floating point number buffer protocol
from number or min(…, key=func) Smallest item of
string iterable or
format(object, Formatted arguments,
format_spec='') representation optionally comparing
value of func(item)
frozenset(…) New frozenset object
next(iterator[, Next item from
getattr(object, Get value of named
default]) iterator, optionally
name[, default]) attribute of object,
return default
else default or
instead of
raise exception
StopIteration
globals() Dictionary of
object() New featureless
current module
object
namespace
oct(number) Convert number to
hasattr(object, True if object has
octal string
name) named attribute
open(file, …) Create file object
hash(object) Hash value of
from path
object, see
string/bytes or
object.__hash__()
integer file
help(…) Built-in help system descriptor
hex(number) Convert number to ord(chr) Integer representing
lowercase Unicode code point
hexadecimal string of character
id(object) Return unique pow(base, exp, Return base to the
integer identifier mod=None) power of exp
of object
print(*values, sep=' Print object to
__import__(name, …) Invoked by the ', end='\n', sys.stdout, or text
import statement file=sys.stdout, stream file
flush=False)
input(prompt='') Read string from
sys.stdin, with property(…) Property decorator
optional prompt
range(…) Generate integer
int(…) Create integer from sequence
number or string
repr(object) String
isinstance(object, True if object is representation of
cls_or_tuple) instance of given object for debugging
class(es)
reversed(sequence) Reverse iterator
issubclass(cls, True if class is
cls_or_tuple) subclass of given
class(es)

2 of 26 © kieranholland.com
The *Best Python Cheat Sheet

round(number, Number rounded to sum(iterable, Sums items of


ndigits=None) ndigits precision start=0) iterable, optionally
after decimal point adding start value
set(…) New set object super(…) Proxy object that
delegates method
setattr(object, Set object attribute
calls to parent or
name, value) value by name
sibling
slice(…) Slice object
tuple(iterable) Create a tuple
representing a set
of indices type(…) Type of an object,
or build new type
sorted(iterable, New sorted list from
key=func, the items in vars([object]) Return
reverse=False) iterable, optionally object.__dict__ or
comparing value of locals() if no
func(item) argument
staticmethod(func) Transform function zip(*iterables, Iterate over
into static method strict=False) multiple iterables
in parallel, strict
str(…) String description
requires equal
of object
length

Operator
Precedence (high->low) Description
(…,) […,] {…,} {…:…,} tuple, list, set, dict
s[i] s[i:j] s.attr f(…) index, slice, attribute, function call
await x await expression
+x, -x, ~x unary positive, negative, bitwise NOT
x ** y power
x * y, x @ y, x / y, x // y, x % y multiply, maxtrix multiply, divide, floor
divide, modulus
x + y, x - y add, substract
x << y x >> y bitwise shift left, right
x & y bitwise and
x ^ y bitwise exclusive or
x | y bitwise or
x<y x<=y x>y x>=y x==y x!=y comparison,
x is y x is not y identity,
x in s x not in s membership
not x boolean negation
x and y boolean and
x or y boolean or
… if … else … conditional expression
lambda lambda expression
:= assignment expression

© kieranholland.com 3 of 26
The *Best Python Cheat Sheet

Assignment Usually equivalent


a = b Assign object b to label a
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a / b (true division)
a //= b a = a // b (floor division)
a %= b a = a % b
a **= b a = a ** b
a &= b a = a & b
a |= b a = a | b
a ^= b a = a ^ b
a >>= b a = a >> b
a <<= b a = a << b
Assignment expression
Assign and return value using the walrus operator.

count = 0
while (count := count + 1) < 5:
print(count)

>>> z = [1, 2, 3, 4, 5]
>>> [x for i in z if (x:=i**2) > 10]
[16, 25]

Assignment unpacking
Unpack multiple values to a name using the splat operator.

head, *body = s # assign first value of s to head, remainder to body


head, *body, tail = s # assign first and last values of s to head and tail,
remainder to body
*body, tail = s # assign last value of s to tail, remainder to body
s = [*iterable[, …]] # unpack iterable to list
s = (*iterable[, …]) # unpack iterable to tuple
s = {*iterable[, …]} # unpack iterable to set
d2 = {**d1[, …]} # unpack mapping to dict

Flow control

for item in <iterable>:



[else: # only if loop completes without break
…]

while <condition>:

[else: # only if loop completes without break
…]

break # immediately exit loop


continue # skip to next loop iteration
return[ value] # exit function, return value | None
yield[ value] # exit generator, yield value | None
assert <expr>[, message] # if not <expr> raise AssertionError([message])

4 of 26 © kieranholland.com
The *Best Python Cheat Sheet

if <condition>:

[elif <condition>:
…]*
[else:
…]

<expression1> if <condition> else <expression2>

with <expression>[ as name]: # context manager


Context manager
A with statement takes an object with special methods:
◼ __enter__() - locks resources and optionally returns an object
◼ __exit__() - releases resources, handles any exception raised in the block,
optionally suppressing it by returning True

class AutoClose:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.f = open(self.filename)
return self.f
def __exit__(self, exc_type, exception, traceback):
self.f.close()

>>> with AutoClose('test.txt') as f:


... print(f.read())
Hello world!

Match
3.10+

match <expression>:
case <pattern>[ if <condition>]: # conditional match, if "guard" clause

case <pattern1> | <pattern2>: # OR pattern

case _: # default case

Match case pattern


1/'abc'/True/None/math.pi Value pattern, match literal or dotted name
<name> Capture pattern, match any object and bind to name
_ Wildcard pattern, match any object
<type>() Class pattern, match any object of that type
<type>(<attr>=<pattern|name>, …) Class pattern, match object with matching
attributes
<pattern> | <pattern> [| …] Or pattern, match any of the patterns left to
right
[<pattern>[, …[, *args]] Sequence pattern (list|tuple), match any sequence
with matching items (but not string or iterator),
may be nested
{<value_pattern>: <pattern>[, …[, Mapping pattern, match dictionary with matching
**kwds]]} items, may be nested

© kieranholland.com 5 of 26
The *Best Python Cheat Sheet

<pattern> as <name> Bind match to name


<builtin>(<name>) Builtin pattern, shortcut for <builtin>() as
<name> (e.g. str, int)

◼ Class patterns
◼ Do not create a new instance of the class
◼ Accept positional parameters if class defines __match_args__ special attribute
(e.g. dataclass)
◼ Sequence patterns support assignment unpacking
◼ Names bound in a match statement are visible after the match statement

Scope
Scope levels:
Builtin Names pre-assigned in Generator Names contained within
builtins module expression generator expression
Module (global) Names defined in current Comprehension Names contained within
module comprehension
Note: Code in global
Class Names shared across all
scope cannot access
instances
local variables
Instance Names contained within a
Enclosing Names defined in any
specific instance
(closure) enclosing functions
Method Names contained within a
Function Names defined in current
specific instance method
(local) function
Note: By default, has
read-only access to
module and enclosing
function names
By default, assignment
creates a new local name
global <name> grants
read/write access to
specified module name
nonlocal <name> grants
read/write access to
specified name in
closest enclosing
function defining that
name

◼ globals() - return Dictionary of module scope variables


◼ locals() - return Dictionary of local scope variables

6 of 26 © kieranholland.com
The *Best Python Cheat Sheet

>>> global_name = 1
>>> def read_global():
... print(global_name)
... local_name = "only available in this function"
>>> read_global()
1
>>> def write_global():
... global global_name # enable write to global
... global_name = 2
>>> write_global()
>>> print(global_name)
2
>>> def write_nonlocal():
... closure_name = 1
... def nested():
... nonlocal closure_name # enable write to nonlocal
... closure_name = 2
... nested()
... print(closure_name)
>>> write_nonlocal()
2

class C:
class_name = 1 # shared by all instances
def __init__(self):
self.instance_name = 2 # only on this instance
def method(self):
self.instance_name = 3 # update instance name
C.class_name = 3 # update class name
method_name = 1 # set method local name

Sequence
Operations on sequence types (Bytes, List, Tuple, String).
x in s True if any s[i] == x s.index(x[, Smallest i where s[i] ==
start[, stop]]) x, start/stop bounds
x not in s True if no s[i] == x
search
s1 + s2 Concatenate s1 and s2
reversed(s) Iterator on s in reverse
s * n, n * s Concatenate n copies of order
s For string use
s.count(x) Count of s[i] == x reversed(list(s))

len(s) Count of items sorted(s, New sorted list


cmp=func,
min(s) Smallest item of s key=getter,
max(s) Largest item of s reverse=False)

Indexing
Select items from sequence by index or slice.

© kieranholland.com 7 of 26
The *Best Python Cheat Sheet

>>> s = [0, 1, 2, 3, 4]
>>> s[0] # 0-based indexing
0
>>> s[-1] # negative indexing from end
4
>>> s[slice(2)] # slice(stop) - index from 0 until stop (exclusive)
[0, 1]
>>> s[slice(1, 5, 3)] # slice(start, stop[, step]) - index from start to stop
(exclusive), with optional step size (+|-)
[1, 4]
>>> s[:2] # slices are created implicitly when indexing with ':'
[start:stop:step]
[0, 1]
>>> s[3::-1] # negative step
[3, 2, 1, 0]
>>> s[1:3]
[1, 2]
>>> s[1:5:2]
[1, 3]

Comparison
◼ A sortable class should define __eq__(), __lt__(), __gt__(), __le__() and __ge__()
special methods.
◼ With functools @total_ordering decorator a class need only provide __eq__() and
one other comparison special method.
◼ Sequence comparison: values are compared in order until a pair of unequal values
is found. The comparison of these two values is then returned. If all values are
equal, the shorter sequence is lesser.

from functools import total_ordering

@total_ordering
class C:
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

Tuple
Immutable hashable sequence.
s = () Empty tuple
s = (1, 'a', 3.0) Create from items
s = 1, 'a', 3.0
s = (1,) Single-item tuple
(1, 2, 3) == (1, 2) + (3,) Add makes new tuple
(1, 2, 1, 2) == (1, 2) * 2 Multiply makes new tuple

Named tuple
Tuple subclass with named items. Also: typing.NamedTuple

8 of 26 © kieranholland.com
The *Best Python Cheat Sheet

>>> from collections import namedtuple


>>> Point = namedtuple('Point', ('x', 'y')) # or namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.y
2

List
Mutable non-hashable sequence.
s = [] Empty list s.extend(it) Add items from iterable
s[len(s):len(s) to end
s = [1, 'a', Create from items
] = it
3.0]
s = s.insert(i, x) Insert item at index i
list(range(3)) s[i:i] = [x]
s[i] = x Replace item index i s.remove(x) Remove first item where
with x del s[i] == x
s[s.index(x)]
s[<slice>] = it Replace slice with
iterable y = s.pop([i]) Remove and return last
item or indexed item
del s[<slice>] Remove slice
s[<slice>] = [] s.reverse() Reverse items in place
s.append(x) Add item to end s.sort(cmp=func Sort items in place,
s += x , key=getter, default ascending
s[len(s):len(s) reverse=False)
] = [x]

List comprehension

result = [<expression> for item1 in <iterable1>{ if <condition1>}


{for item2 in <iterable2>{ if <condition2>} … for itemN in <iterableN>{
if <conditionN>}}]

# is equivalent to:

result = []
for item1 in <iterable1>:
for item2 in <iterable2>:

for itemN in <iterableN>:
if <condition1> and <condition2> … and <conditionN>:
result.append(<expression>)

Dictionary
Mutable non-hashable key:value pair mapping.
dict() Empty dict dict.fromkeys(keys, Create from keys,
{} value=None) all set to value
dict(<sequence|mappi Create from d.keys() Iterable of keys
ng>) key:value pairs
d.values() Iterable of values
{'d':4, 'a':2}
d.items() Iterable of (key,
dict(**kwds) Create from keyword
value) pairs
arguments
d.get(key, Get value for key,
dict(zip(keys, Create from
default=None) or default
values)) sequences of keys
and values

© kieranholland.com 9 of 26
The *Best Python Cheat Sheet

d.setdefault(key, Get value for key, d.clear() Remove all items


default=None) add if missing
d.copy() Shallow copy
d.pop(key) Remove and return
d1.update(d2) Add/replace
value for key, raise
d1 |= d2 3.9+ key:value pairs from
KeyError if missing
d2 to d1
d.popitem() Remove and return
d3 = d1 | d2 3.9+ Merge to new dict,
(key, value) pair
d3 = {**d1, **d2} d2 trumps d1
(last-in, first-out)

# defaultdict(<callable>) sets default value returned by callable()


import collections
collections.defaultdict(lambda: 42) # dict with default value 42

Dict comprehension

# {k: v for k, v in <iterable>[ if <condition>]}

>>> {x: x**2 for x in (2, 4, 6) if x < 5}


{2: 4, 4: 16}

Set
Mutable (set) and immutable (frozenset) sets.
set() Empty set s.clear() [mutable] Remove all elements
frozenset()
s1.intersection(s2[, New set of shared
{1, 2, 3} Create from items, s3…]) elements
note: {} creates s1 & s2
empty dict - sad!
s1.intersection_upda Update s1 to
set(iterable) Create from iterable te(s2) [mutable] intersection with s2
{*iterable}
s1.union(s2[, s3…]) New set of all
len(s) Cardinality s1 | s2 elements
v in s Test membership s1.difference(s2[, New set of elements
v not in s s3…]) unique to s1
s1 - s2
s1.issubset(s2) True if s1 is subset
of s2 s1.difference_update Remove s1 elements
(s2) [mutable] intersecting with s2
s1.issuperset(s2) True if s1 is
superset of s2 s1.symmetric_differe New set of unshared
nce(s2) elements
s.add(v) [mutable] Add element
s1 ^ s2
s.remove(v) Remove element
s1.symmetric_differe Update s1 to
[mutable] (KeyError if not
nce_update(s2) symmetric difference
found)
[mutable] with s2
s.discard(v) Remove element if
s.copy() Shallow copy
[mutable] present
s.update(it1[, Add elements from
s.pop() [mutable] Remove and return
it2…]) [mutable] iterables
arbitrary element
(KeyError if empty)

Set comprehension

# {x for x in <iterable>[ if <condition>]}

>>> {x for x in 'abracadabra' if x not in 'abc'}


{'r', 'd'}

Bytes
Immutable sequence of bytes. Mutable version is bytearray.

10 of 26 © kieranholland.com
The *Best Python Cheat Sheet

b'abc\x42' Create from ASCII <bytes> = Return bytes even if


characters and \x00-\xff <bytes> only one element
[<slice>]
bytes(<ints>) Create from int sequence
list(<bytes>) Return ints in range 0
bytes(<str>, Create from string
to 255
'utf-8')
<str>.encode('u <bytes_sep>.joi Join byte_objs sequence
tf-8') n(<byte_objs>) with bytes_sep separator
<int>.to_bytes( Create from int str(<bytes>, Convert bytes to string
length, order, (order='big'|'little') 'utf-8')
signed=False) <bytes>.decode(
'utf-8')
bytes.fromhex(' Create from hex pairs
<hex>') (can be separated by int.from_bytes( Return int from bytes
whitespace) bytes, order, (order='big'|'little')
signed=False)
<int> = <bytes> Return int in range 0 to
[<index>] 255 <bytes>.hex(sep Return hex pairs
='',
bytes_per_sep=2
)

def read_bytes(filename):
with open(filename, 'rb') as f:
return f.read()

def write_bytes(filename, bytes_obj):


with open(filename, 'wb') as f:
f.write(bytes_obj)

Function
Function definition

# var-positional
def f(*args): … # f(1, 2)
def f(x, *args): … # f(1, 2)
def f(*args, z): … # f(1, z=2)

# var-keyword
def f(**kwds): … # f(x=1, y=2)
def f(x, **kwds): … # f(x=1, y=2) | f(1, y=2)

def f(*args, **kwds): … # f(x=1, y=2) | f(1, y=2) | f(1, 2)


def f(x, *args, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) |
f(1, 2, 3)
def f(*args, y, **kwds): … # f(x=1, y=2, z=3) | f(1, y=2, z=3)

# positional-only before /
def f(x, /, y): … # f(1, 2) | f(1, y=2)
def f(x, y, /): … # f(1, 2)

# keyword-only after *
def f(x, *, y): … # f(x=1, y=2) | f(1, y=2)
def f(*, x, y): … # f(x=1, y=2)

Function call

args = (1, 2) # * expands sequence to positional arguments


kwds = {'x': 3, 'y': 4} # ** expands dictionary to keyword arguments
func(*args, **kwds) # is the same as:
func(1, 2, x=3, y=4)

© kieranholland.com 11 of 26
The *Best Python Cheat Sheet

Class
Instantiation

class C:
"""Class docstring."""
def __init__(self, a):
"""Method docstring."""
self.a = a
def __repr__(self):
"""Used for repr(c), also for str(c) if __str__ not defined."""
return f'{self.__class__.__name__}({self.a!r})'
def __str__(self):
"""Used for str(c), e.g. print(c)"""
return str(self.a)
@classmethod
def get_class_name(cls): # passed class rather than instance
return cls.__name__
@staticmethod
def static(): # passed nothing
return 1

>>> c = C(2) # instantiate

# under the covers, class instantiation does this:


obj = cls.__new__(cls, *args, **kwds)
if isinstance(obj, cls):
obj.__init__(*args, **kwds)

Instance property

class C:
@property
def f(self):
if not hasattr(self, '_f'):
return
return self._f
@f.setter
def f(self, value):
self._f = value

12 of 26 © kieranholland.com
The *Best Python Cheat Sheet

Class special methods


Operator Method
self + other __add__(self, other)
other + self __radd__(self, other)
self += other __iadd__(self, other)
self - other __sub__(self, other)
other - self __rsub__(self, other)
self -= other __isub__(self, other)
self * other __mul__(self, other)
other * self __rmul__(self, other)
self *= other __imul__(self, other)
self @ other __matmul__(self, other)
other @ self __rmatmul__(self, other)
self @= other __imatmul__(self, other)
self / other __truediv__(self, other)
other / self __rtruediv__(self, other)
self /= other __itruediv__(self, other)
self // other __floordiv__(self, other)
other // self __rfloordiv__(self, other)
self //= other __ifloordiv__(self, other)
self % other __mod__(self, other)
other % self __rmod__(self, other)
self %= other __imod__(self, other)
self ** other __pow__(self, other)
other ** self __rpow__(self, other)
self **= other __ipow__(self, other)
self << other __lshift__(self, other)
other << self __rlshift__(self, other)
self <<= other __ilshift__(self, other)
self >> other __rshift__(self, other)
other >> self __rrshift__(self, other)
self >>= other __irshift__(self, other)
self & other __and__(self, other)
other & self __rand__(self, other)
self &= other __iand__(self, other)
self | other __or__(self, other)
other | self __ror__(self, other)
self |= other __ior__(self, other)
self ^ other __xor__(self, other)
other ^ self __rxor__(self, other)
self ^= other __ixor__(self, other)
divmod(self, other) __divmod__(self, other)
divmod(self, other) __rdivmod__(self, other)

© kieranholland.com 13 of 26
The *Best Python Cheat Sheet

Operator Method
-self __neg__(self)
+self __pos__(self)
abs(self) __abs__(self)
~self __invert__(self) [bitwise]
self == other __eq__(self) [default 'is', requires __hash__]
self != other __ne__(self)
self < other __lt__(self, other)
self <= other __le__(self, other)
self > other __gt__(self, other)
self >= other __ge__(self, other)
item in self __contains__(self, item)
bool(self) __bool__(self)
if self:
if not self:
bytes(self) __bytes__(self)
complex(self) __complex__(self)
float(self) __float__(self)
int(self) __int__(self)
round(self) __round__(self[, ndigits])
math.ceil(self) __ceil__(self)
math.floor(self) __floor__(self)
math.trunc(self) __trunc__(self)
dir(self) __dir__(self)
format(self) __format__(self, format_spec)
hash(self) __hash__(self)
iter(self) __iter__(self)
len(self) __len__(self)
repr(self) __repr__(self)
reversed(self) __reversed__(self)
str(self) __str__(self)
self(*args, **kwds) __call__(self, *args, **kwds)
self[…] __getitem__(self, key)
self[…] = 1 __setitem__(self, key, value)
del self[…] __delitem__(self, key)
other[self] __index__(self)
self.name __getattribute__(self, name)
__getattr__(self, name) [if AttributeError]
self.name = 1 __setattr__(self, name, value)
del self.name __delattr__(self, name)
with self: __enter__(self)
__exit__(self, exc_type, exc_value, traceback)
await self __await__(self)

Decorator
Decorator syntax passes a function or class to a callable and replaces it with the
return value.

14 of 26 © kieranholland.com
The *Best Python Cheat Sheet

def show_call(obj):
"""
Decorator that prints obj name and arguments each time obj is called.
"""
def show_call_wrapper(*args, **kwds):
print(obj.__name__, args, kwds)
return obj(*args, **kwds)
return show_call_wrapper

@show_call # function decorator


def add(x, y):
return x + y

# is equivalent to
add = show_call(add)

>>> add(13, 29)


add (13, 29) {}
42

@show_call # class decorator


class C:
def __init__(self, a=None):
pass

# is equivalent to
C = show_call(C)

>>> C(a=42)
C () {'a': 42}

© kieranholland.com 15 of 26
The *Best Python Cheat Sheet

# decorators optionally take arguments


def show_call_if(condition):
"""
Apply show_call decorator only if condition is True.
"""
return show_call if condition else lambda obj: obj

@show_call_if(False)
def add(x, y):
return x + y

# is equivalent to
add = show_call_if(False)(add)

>>> add(13, 29)


42

@show_call_if(True)
def add(x, y):
return x + y

>>> add(13, 29)


add (13, 29) {}
42

>>> add.__name__
'show_call_wrapper' # ugh! decorated function has different metadata

# @wraps decorator copies metadata of decorated object to wrapped object


# preserving original attributes (e.g. __name__)
from functools import wraps

def show_call_preserve_meta(obj):
@wraps(obj)
def show_call_wrapper(*args, **kwds):
print(obj.__name__, args, kwds)
return obj(*args, **kwds)
return show_call_wrapper

@show_call_preserve_meta
def add(x, y):
return x + y

>>> add.__name__
'add'

Iterator
An iterator implements the __iter__() method, returning an iterable that implements
the __next__() method. The __next__() method returns the next item in the collection
and raises StopIteration when done.

16 of 26 © kieranholland.com
The *Best Python Cheat Sheet

class C:
def __init__(self, items):
self.items = items

def __iter__(self):
"""Make class its own iterable."""
return self

def __next__(self):
"""Implement to be iterable."""
if self.items:
return self.items.pop()
raise StopIteration

>>> c = C([13, 29])


>>> it = iter(c) # get iterator
>>> next(it) # get next item
29
>>> for item in c: # iterate over C instance
... print(item)
13

Generator
A function with a yield statement returns a generator iterator and suspends function
processing. Each iteration over the generator iterator resumes function execution,
returns the next yield value, and suspends again.

def gen():
"""Generator function"""
for i in [13, 29]:
yield i

>>> g = gen()
>>> next(g) # next value
13
>>> for item in gen(): # iterate over values
... print(item)
13
29
>>> list(gen()) # list all values
[13, 29]

def parent_gen():
yield from gen() # delegate yield to another generator

>>> list(parent_gen())
[13, 29]

Generator expression

# (<expression> for <name> in <iterable>[ if <condition>])


>>> g = (item for item in [13, 29] if item > 20)
>>> list(g)
[29]

String
Immutable sequence of characters.

© kieranholland.com 17 of 26
The *Best Python Cheat Sheet

<substring> in s True if string s.casefold() To lower case


contains substring (aggressive)
s.startswith(<prefix True if string s.upper() To upper case
>[, start[, end]]) starts with prefix,
s.title() To title case (The
optionally search
Quick Brown Fox)
bounded substring
s.capitalize() Capitalize first
s.endswith(<suffix> True if string ends
letter
[, start[, end]]) with suffix,
optionally search s.swapcase() Swap case
bounded substring s.replace(old, new[, Replace old with new
s.strip(chars=None) Strip whitespace count]) at most count times
from both ends, or s.translate(<table>) Use
passed characters str.maketrans(<dict>
s.lstrip(chars=None) Strip whitespace ) to generate table
from left end, or s.expandtabs(tabsize Expand tabs to
passed characters =8) spaces
s.rstrip(chars=None) Strip whitespace chr(<int>) Integer to Unicode
from right end, or character
passed characters
ord(<str>) Unicode character to
s.ljust(width, Left justify with integer
fillchar=' ') fillchar
<str>.encode(encodin Encode string to
s.rjust(width, Right justify with g='utf-8', bytes
fillchar=' ') fillchar errors='strict')
s.center(width, Center with fillchar s.isalnum() True if isnumeric()
fillchar=' ') or [a-zA-Z…] (>0
s.split(sep=None, Split on whitespace, characters)
maxsplit=-1) or sep str at most s.isalpha() True if [a-zA-Z…]
maxsplit times (>0 characters)
s.splitlines(keepend Split lines on s.isdecimal() True if [0-9], [०-९]
s=False) [\n\r\f\v\x1c- or [٩-٠] (>0
\x1e\x85\u2028\u2029 characters)
] and \r\n
s.isdigit() True if isdecimal()
<separator>.join(<st Join sequence of or [²³¹…] (>0
rings>) strings with characters)
separator string
s.isidentifier() True if valid Python
s.format(*args, Substitute arguments name (including
**kwds) into {} placeholders keywords)
s.format_map(mapping Substitute mapping s.islower() True if all
) into {} placeholders characters are lower
s.find(<substring>) Index of first match case (>0 characters)
or -1 s.isnumeric() True if isdigit() or
s.rfind(<substring>) Index of last match [¼½¾零〇一 …] (>0
or -1 characters)
s.index(<substring>) Index of first match s.isprintable() True if isalnum() or
or raise ValueError [ !#$%…] (>0
characters)
s.rindex(<substring> Index of last match
) or raise ValueError s.isspace() True if [
\t\n\r\f\v\x1c-
s.count(<substring> Count instances of
\x1f\x85\xa0…] (>0
[, start[, end]]) substring,
characters)
optionally search
bounded substring s.istitle() True if string is
title case (>0
s.lower() To lower case
characters)

18 of 26 © kieranholland.com
The *Best Python Cheat Sheet

s.isupper() True if all head, sep, tail = Search for separator


characters are upper s.rpartition(<separa from end and split
case (>0 characters) tor>)
head, sep, tail = Search for separator s.removeprefix(<pref Remove prefix if
s.partition(<separat from start and split ix>) 3.9+ present
or>)
s.removesuffix(<suff Remove suffix if
ix>) 3.9+ present

String escape
Sequence Escape
Literal backslash \\
Single quote \'
Double quote \"
Backspace \b
Carriage return \r
Newline \n
Tab \t
Vertical tab \v
Null \0
Hex value \xff
Octal value \o77
Unicode 16 bit \uxxxx
Unicode 32 bit \Uxxxxxxxx
Unicode name \N{name}
String formatting
Format f-string Output
Escape curly braces f"{{}}" '{}'
Expression f"{6/3}, {'a'+'b'}" '2, ab'
'{}, {}'.format(6/3,
'a'+'b')
Justify left f'{1:<5}' '1 '
Justify center f'{1:^5}' ' 1 '
Justify right f'{1:>5}' ' 1'
Justify left with char f'{1:.<5}' '1....'
Justify right with char f'{1:.>5}' '....1'
Trim f"{'abc':.2}" 'ab'
Trim justify left f"{'abc':6.2}" 'ab '
ascii() f'{v!a}' ascii(v)
repr() f'{v!r}' repr(v)
str() f'{v!s}' str(v)
Justify left repr() f"{'abc'!r:6}" "'abc' "
Date format f'{today:%d %b %Y}' '21 Jan 1984'

© kieranholland.com 19 of 26
The *Best Python Cheat Sheet

Format f-string Output


Significant figures f'{1.234:.2}' '1.2'
Fixed-point notation f'{1.234:.2f}' '1.23'
Scientific notation f'{1.234:.2e}' '1.230e+00'
Percentage f'{1.234:.2%}' '123.40%'
Pad with zeros f'{1.7:04}' '01.7'
Pad with spaces f'{1.7:4}' ' 1.7'
Pad before sign f'{123:+6}' ' +123'
Pad after sign f'{123:=+6}' '+ 123'
Separate with commas f'{123456:,}' '123,456'
Separate with underscores f'{123456:_}' '123_456'
f'{1+1=}' f'{1+1=}' '1+1=2' (= prepends)
Binary f'{164:b}' '10100100'
Octal f'{164:o}' '244'
Hex f'{164:X}' 'A4'
chr() f'{164:c}' 'ÿ'

Regex
Standard library re module provides Python regular expressions.

>>> import re
>>> my_re = re.compile(r'name is (?P<name>[A-Za-z]+)')
>>> match = my_re.search('My name is Douglas.')
>>> match.group()
'name is Douglas'
>>> match.group(1)
'Douglas'
>>> match.groupdict()['name']
'Douglas'

Regex syntax
. Any character (newline if | Or
DOTALL)
(…) Group
^ Start of string (every line if
(?:…) Non-capturing group
MULTILINE)
(? Named group
$ End of string (every line if
P<name>…)
MULTILINE)
(?P=name) Match text matched by earlier
* 0 or more of preceding
group
+ 1 or more of preceding
(?=…) Match next, non-consumptive
? 0 or 1 of preceding
(?!…) Non-match next, non-
*?, +?, Same as *, + and ?, as few as consumptive
?? possible
(?<=…) Match preceding, positive
{m,n} m to n repetitions lookbehind assertion
{m,n}? m to n repetitions, as few as (?<!…) Non-match preceding, negative
possible lookbehind assertion
[…] Character set: e.g. '[a-zA-Z]' (? Conditional match - A if group
(group)A| previously matched else B
[^…] NOT character set
B)
\ Escape chars '*?+&$|()',
(? Set flags for RE ('i','L',
introduce special sequences
letters) 'm', 's', 'u', 'x')
\\ Literal '\'
(?#…) Comment (ignored)

20 of 26 © kieranholland.com
The *Best Python Cheat Sheet

Regex special sequences


\<n> Match by integer group \s Whitespace [ \t\n\r\f\v] (see
reference starting from 1 flag: ASCII)
\A Start of string \S Non-whitespace (see flag:
ASCII)
\b Word boundary (see flag:
ASCII|LOCALE) \w Alphanumeric (see flag:
ASCII|LOCALE)
\B Not word boundary (see flag:
ASCII|LOCALE) \W Non-alphanumeric (see flag:
ASCII|LOCALE)
\d Decimal digit (see flag:
ASCII) \Z End of string
\D Non-decimal digit (see flag:
ASCII)

Regex flags
Flags modify regex behaviour. Pass to regex functions (e.g. re.A | re.ASCII) or embed
in regular expression (e.g. (?a)).
(?a) | A | ASCII ASCII-only match for (?m) | M | MULTILINE Match every new
\w, \W, \b, \B, \d, line, not only
\D, \s, \S (default start/end of string
is Unicode)
(?s) | S | DOTALL '.' matches ALL
(?i) | I | Case insensitive chars, including
IGNORECASE matching newline
(?L) | L | LOCALE Apply current locale (?x) | X | VERBOSE Ignores whitespace
for \w, \W, \b, \B outside character
(discouraged) sets
DEBUG Display expression
debug info

Regex functions
compile(pattern[, Compiles findall(pattern, Non-overlapping
flags=0]) Regular Expression Ob string) matches as list of
groups or tuples
escape(string) Escape non-
(>1)
alphanumerics
finditer(pattern, Iterator over non-
match(pattern, Match from start
string[, flags]) overlapping matches
string[, flags])
sub(pattern, repl, Replace count first
search(pattern, Match anywhere
string[, count=0]) leftmost non-
string[, flags])
overlapping; If repl
split(pattern, Splits by pattern, is function, called
string[, keeping splitter if with a MatchObj
maxsplit=0]) grouped
subn(pattern, repl, Like sub(), but
string[, count=0]) returns (newString,
numberOfSubsMade)

Regex object
flags Flags split(string[, See split() function
maxsplit=0])
groupindex {group name: group
number} findall(string[, See findall()
pos[, endpos]]) function
pattern Pattern
finditer(string[, See finditer()
match(string[, pos] Match from start of
pos[, endpos]]) function
[, endpos]) target[pos:endpos]
sub(repl, string[, See sub() function
search(string[, pos] Match anywhere in
count=0])
[, endpos]) target[pos:endpos]
subn(repl, string[, See subn() function
count=0])

© kieranholland.com 21 of 26
The *Best Python Cheat Sheet

Regex match object


pos pos passed to search or start(group Indices of start & end of
match ), group match (None if group
end(group) exists but didn't
endpos endpos passed to search or
contribute)
match
span(group) (start(group), end(group));
re RE object
(None, None) if group didn't
group([g1, One or more groups of match contibute
g2, ...]) One arg, result is a string
string String passed to match() or
Multiple args, result is
search()
tuple
If gi is 0, returns the
entire matching string
If 1 <= gi <= 99, returns
string matching group
(None if no such group)
May also be a group name
Tuple of match groups
Non-participating groups are
None
String if len(tuple)==1

Number
bool([object]) Boolean, see __bool__
True, False special method
int([float|str|bool]) Integer, see __int__
5 special method
float([int|str|bool]) Float (inexact, compare with
5.1, 1.2e-4 math.isclose(<float>, <float>)
See __float__ special method
complex(real=0, imag=0) Complex, see __complex__
3 - 2j, 2.1 + 0.8j special method
fractions.Fraction(<numerator>, <denominator>) Fraction
decimal.Decimal([str|int]) Decimal (exact, set precision:
decimal.getcontext().prec =
<int>)
bin([int]) Binary
0b101010
int('101010', 2)
int('0b101010', 0)
hex([int]) Hex
0x2a
int('2a', 16)
int('0x2a', 0)

Mathematics

from math import (e, pi, inf, nan, isinf, isnan,


sin, cos, tan, asin, acos, atan, degrees, radians,
log, log10, log2)

Also: built-in functions (abs, max, min, pow, round, sum)


Statistics

from statistics import mean, median, variance, stdev, quantiles, groupby

22 of 26 © kieranholland.com
The *Best Python Cheat Sheet

Random

>>> from random import random, randint, choice, shuffle, gauss, triangular, seed
>>> random() # float inside [0, 1)
0.42
>>> randint(1, 100) # int inside [<from>, <to>]
42
>>> choice(range(100)) # random item from sequence
42

Time
The datetime module provides immutable hashable date, time, datetime, and
timedelta classes.
Time formatting
Code Output
%a Day name short (Mon)
%A Day name full (Monday)
%b Month name short (Jan)
%B Month name full (January)
%c Locale datetime format
%d Day of month [01,31]
%f Microsecond [000000,999999]
%H Hour (24-hour) [00,23]
%I Hour (12-hour) [01,12]
%j Day of year [001,366]
%m Month [01,12]
%M Minute [00,59]
%p Locale format for AM/PM
%S Second [00,61]. Yes, 61!
%U Week number (Sunday start) [00(partial),53]
%w Day number [0(Sunday),6]
%W Week number (Monday start) [00(partial),53]
%x Locale date format
%X Locale time format
%y Year without century [00,99]
%Y Year with century (2023)
%Z Time zone ('' if no TZ)
%z UTC offset (+HHMM/-HHMM, '' if no TZ)
%% Literal '%'

© kieranholland.com 23 of 26
The *Best Python Cheat Sheet

Exception

try:

[except [<Exception>[ as e]]:
…]
[except: # catch all
…]
[else: # if no exception
…]
[finally: # always executed
…]

raise <exception>[ from <exception|None>]

try:
1 / 0
except ZeroDivisionError:
# from None hides exception context
raise TypeError("Hide ZeroDivisionError") from None

24 of 26 © kieranholland.com
The *Best Python Cheat Sheet

BaseException Base class for all exceptions


├─ BaseExceptionGroup Base class for groups of exceptions
├─ GeneratorExit Generator close() raises to terminate iteration
├─ KeyboardInterrupt On user interrupt key (often 'CTRL-C')
├─ SystemExit On sys.exit()
└─ Exception Base class for errors
├─ ArithmeticError Base class for arithmetic errors
│ ├─ FloatingPointError Floating point operation failed
│ ├─ OverflowError Result too large
│ └─ ZeroDivisionError Argument of division or modulo is 0
├─ AssertionError Assert statement failed
├─ AttributeError Attribute reference or assignment failed
├─ BufferError Buffer operation failed
├─ EOFError input() hit end-of-file without reading data
├─ ExceptionGroup Group of exceptions raised together
├─ ImportError Import statement failed
│ └─ ModuleNotFoundError Module not able to be found
├─ LookupError Base class for lookup errors
│ └─ IndexError Index not found in sequence
│ └─ KeyError Key not found in dictionary
├─ MemoryError Operation ran out of memory
├─ NameError Local or global name not found
│ └─ UnboundLocalError Local variable value not asssigned
├─ OSError System related error
│ ├─ BlockingIOError Non-blocking operation will block
│ ├─ ChildProcessError Operation on child process failed
│ ├─ ConnectionError Base class for connection errors
│ │ ├─ BrokenPipeError Write to closed pipe or socket
│ │ ├─ ConnectionAbortedError Connection aborted
│ │ ├─ ConnectionRefusedError Connection denied by server
│ │ └─ ConnectionResetError Connection reset mid-operation
│ ├─ FileExistsError Trying to create a file that already exists
│ ├─ FileNotFoundError File or directory not found
│ ├─ InterruptedError System call interrupted by signal
│ ├─ IsADirectoryError File operation requested on a directory
│ ├─ NotADirectoryError Directory operation requested on a non-directory
│ ├─ PermissionError Operation has insuffient access rights
│ ├─ ProcessLookupError Operation on process that no longer exists
│ └─ TimeoutError Operation timed out
├─ ReferenceError Weak reference used on garbage collected object
├─ RuntimeError Error detected that doesn't fit other categories
│ ├─ NotImplementedError Operation not yet implemented
│ └─ RecursionError Maximum recursion depth exceeded
├─ StopAsyncIteration Iterator __anext__() raises to stop iteration
├─ StopIteration Iterator next() raises when no more values
├─ SyntaxError Python syntax error
│ └─ IndentationError Base class for indentation errors
│ └─ TabError Inconsistent tabs or spaces
├─ SystemError Recoverable Python interpreter error
├─ TypeError Operation applied to wrong type object
├─ ValueError Operation on right type but wrong value
│ └─ UnicodeError Unicode encoding/decoding error
│ ├─ UnicodeDecodeError Unicode decoding error
│ ├─ UnicodeEncodeError Unicode encoding error
│ └─ UnicodeTranslateError Unicode translation error
└─ Warning Base class for warnings
├─ BytesWarning Warnings about bytes and bytesarrays
├─ DeprecationWarning Warnings about deprecated features
├─ EncodingWarning Warning about encoding problem
├─ FutureWarning Warnings about future deprecations for end users
├─ ImportWarning Possible error in module imports
├─ PendingDeprecationWarning Warnings about pending feature deprecations
├─ ResourceWarning Warning about resource use
├─ RuntimeWarning Warning about dubious runtime behavior
├─ SyntaxWarning Warning about dubious syntax
├─ UnicodeWarning Warnings related to Unicode
└─ UserWarning Warnings generated by user code

© kieranholland.com 25 of 26
The *Best Python Cheat Sheet

Execution

$ python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]


$ python --version
Python 3.10.12
$ python --help[-all] # help-all [3.11+]
# Execute code from command line
$ python -c 'print("Hello, world!")'
# Execute __main__.py in directory
$ python <directory>
# Execute module as __main__
$ python -m timeit -s 'setup here' 'benchmarked code here'
# Optimise execution
$ python -O script.py

# Hide warnings
PYTHONWARNINGS="ignore"
# OR
$ python -W ignore foo.py
# OR
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

# module of executed script is assigned __name__ '__main__'


# so to run main() only if module is executed as script
if __name__ == '__main__':
main()

Environment variables
PYTHONHOME Change location of PYTHONOPTIMIZE Optimise execution (-O)
standard Python
PYTHONWARNINGS Set warning level
libraries
[default/error/always/mo
PYTHONPATH Augment default search dule/once/ignore] (-W)
path for module files
PYTHONPROFILEIM Show module import times
PYTHONSTARTUP Module to execute before PORTTIME (-X)
entering interactive
prompt

sitecustomize.py / usercustomize.py
Before __main__ module is executed Python automatically imports:
◼ sitecustomize.py in the system site-packages directory
◼ usercustomize.py in the user site-packages directory

# Get user site packages directory


$ python -m site --user-site

# Bypass sitecustomize.py/usercustomize.py hooks


$ python -S script.py

26 of 26 © kieranholland.com

You might also like