Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Best Python Cheat Sheet

Uploaded by

maksimus20060923
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Best Python Cheat Sheet

Uploaded by

maksimus20060923
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 (11) Flow control (5) Number (22) String (18)
Class (12) Function (11) Operator (3) Test (26)
Debug (26) Generator (17) Regex (19) 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 from
number byte-integers,
aiter(async_iterable) Asynchronous iterator string, or bytes
for an asynchronous callable(object) True if object is
iterable callable
all(iterable) True if all elements chr(i) One character string
of iterable are true for unicode ordinal i
(all([]) is True) (0 <= i <= 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, name) Delete the named
bool(object) Boolean value of attribute, if object
object, see __bool__ allows
breakpoint(*args, Drop into debugger by dict(…) Create new dictionary
**kwds) calling dir([object]) List of names in the
sys.breakpointhook(*a local scope, or
rgs, **kwds) object.__dir__() or
bytearray(…) New array of bytes attributes
from byte-integers,
string, bytes, or
object with buffer
API

Python 3.8+ | 2024 Jul 16 © kieranholland.com 1 of 26


The *Best Python Cheat Sheet

divmod(x, y) Return (quotient issubclass(cls, True if class is


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

2 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

range(…) Generate integer staticmethod(func) Transform function


sequence into static method
repr(object) String representation str(…) String description of
of object for object
debugging sum(iterable, Sums items of
reversed(sequence) Reverse iterator start=0) iterable, optionally
round(number, Number rounded to adding start value
ndigits=None) ndigits precision super(…) Proxy object that
after decimal point delegates method
set(…) New set object calls to parent or
sibling
setattr(object, name, Set object attribute tuple(iterable) Create a tuple
value) value by name
slice(…) Slice object type(…) Type of an object, or
representing a set of build new type
indices vars([object]) Return
sorted(iterable, New sorted list from object.__dict__ or
key=func, the items in locals() if no
reverse=False) iterable, optionally argument
comparing value of zip(*iterables, Iterate over multiple
func(item) strict=False) iterables in
parallel, strict
requires equal 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

Python 3.8+ | 2024 Jul 16 © 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

4 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

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])

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+

Python 3.8+ | 2024 Jul 16 © kieranholland.com 5 of 26


The *Best Python Cheat Sheet

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
<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 Function (local) Names defined in current
builtins module function
Module (global) Names defined in current Note: By default, has
module read-only access to
Note: Code in global module and enclosing
scope cannot access local function names
variables By default, assignment
creates a new local name
Enclosing Names defined in any global <name> grants
(closure) enclosing functions read/write access to
specified module name
nonlocal <name> grants
read/write access to
specified name in closest
enclosing function
defining that name
Generator Names contained within
expression generator expression

6 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

Comprehension Names contained within Instance Names contained within a


comprehension specific instance
Class Names shared across all Method Names contained within a
instances specific instance method
⯀ globals() - return Dictionary of module scope variables
⯀ locals() - return Dictionary of local scope variables

>>> 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
... global_name = 2
>>> write_global()
>>> print(global_name)
2
>>> def write_nonlocal():
... closure_name = 1
... def nested():
... nonlocal closure_name
... closure_name = 2
... nested()
... print(closure_name)
>>> write_nonlocal()
2

class C:
class_name = 1
def __init__(self):
self.instance_name = 2
def method(self):
self.instance_name = 3
C.class_name = 3
method_name = 1

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] ==
x not in s True if no s[i] == x start[, stop]]) x, start/stop bounds
search
s1 + s2 Concatenate s1 and s2 reversed(s) Iterator on s in reverse
s * n, n * s Concatenate n copies of s order
s.count(x) Count of s[i] == x For string use
reversed(list(s))
len(s) Count of items
sorted(s, New sorted list
min(s) Smallest item of s cmp=func,
max(s) Largest item of s key=getter,
reverse=False)
Indexing
Select items from sequence by index or slice.

Python 3.8+ | 2024 Jul 16 © 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

8 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

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

>>> 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 = [1, 'a', Create from items s[len(s):len(s)] to end
3.0] = it
s = s.insert(i, x) Insert item at index i
list(range(3)) s[i:i] = [x]
s[i] = x Replace item index i with s.remove(x) Remove first item where
x del s[i] == x
s[<slice>] = it Replace slice with s[s.index(x)]
iterable y = s.pop([i]) Remove and return last
del s[<slice>] Remove slice item or indexed item
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(**kwds) Create from keyword
{} arguments
dict(<sequence|mappin Create from key:value dict(zip(keys, Create from sequences
g>) pairs values)) of keys and values
{'d':4, 'a':2}

Python 3.8+ | 2024 Jul 16 © kieranholland.com 9 of 26


The *Best Python Cheat Sheet

dict.fromkeys(keys, Create from keys, all d.pop(key) Remove and return


value=None) set to value value for key, raise
d.keys() Iterable of keys KeyError if missing
d.values() Iterable of values d.popitem() Remove and return
(key, value) pair
d.items() Iterable of (key, (last-in, first-out)
value) pairs
d.clear() Remove all items
d.get(key, Get value for key, or
default=None) default d.copy() Shallow copy
d.setdefault(key, Get value for key, d1.update(d2) Add/replace key:value
default=None) add if missing d1 |= d2 3.9+ pairs from d2 to d1
d3 = d1 | d2 3.9+ Merge to new dict, d2
d3 = {**d1, **d2} trumps d1

# 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_updat Update s1 to
set(iterable) Create from iterable e(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.issubset(s2) True if s1 is subset s1 - s2
of s2 s1.difference_update( Remove s1 elements
s1.issuperset(s2) True if s1 is s2) [mutable] intersecting with s2
superset of s2 s1.symmetric_differen New set of unshared
s.add(v) [mutable] Add element ce(s2) elements
s1 ^ s2
s.remove(v) [mutable] Remove element
(KeyError if not s1.symmetric_differen Update s1 to
found) ce_update(s2) symmetric difference
[mutable] with s2
s.discard(v) Remove element if s.copy() Shallow copy
[mutable] present
s.pop() [mutable] Remove and return s.update(it1[, it2…]) Add elements from
arbitrary element [mutable] iterables
(KeyError if empty)

10 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

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.
b'abc\x42' Create from ASCII <bytes> = Return bytes even if only
characters and \x00-\xff <bytes>[<slice>] one element
bytes(<ints>) Create from int sequence list(<bytes>) Return ints in range 0 to
bytes(<str>, Create from string 255
'utf-8') <bytes_sep>.join Join byte_objs sequence
<str>.encode('ut (<byte_objs>) with bytes_sep separator
f-8') str(<bytes>, Convert bytes to string
<int>.to_bytes(l Create from int 'utf-8')
ength, order, (order='big'|'little') <bytes>.decode('
signed=False) utf-8')
bytes.fromhex('< Create from hex pairs int.from_bytes(b Return int from bytes
hex>') (can be separated by ytes, order, (order='big'|'little')
whitespace) signed=False)
<int> = <bytes> Return int in range 0 to <bytes>.hex(sep= Return hex pairs
[<index>] 255 '',
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

Python 3.8+ | 2024 Jul 16 © kieranholland.com 11 of 26


The *Best Python Cheat Sheet

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)

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)

12 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

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

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)

Python 3.8+ | 2024 Jul 16 © 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 Python 3.8+ | 2024 Jul 16


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}

Python 3.8+ | 2024 Jul 16 © 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 Python 3.8+ | 2024 Jul 16


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]

Python 3.8+ | 2024 Jul 16 © kieranholland.com 17 of 26


The *Best Python Cheat Sheet

String
Immutable sequence of characters.
<substring> in s True if string s.lower() To lower case
contains substring s.upper() To upper case
s.startswith(<prefix> True if string starts s.title() To title case (The
[, start[, end]]) with prefix, Quick Brown Fox)
optionally search
bounded substring s.capitalize() Capitalize first
s.endswith(<suffix>[, True if string ends letter
start[, end]]) with suffix, s.replace(old, new[, Replace old with new
optionally search count]) at most count times
bounded substring s.translate(<table>) Use
s.strip(chars=None) Strip whitespace from str.maketrans(<dict>)
both ends, or passed to generate table
characters chr(<int>) Integer to Unicode
s.lstrip(chars=None) Strip whitespace from character
left end, or passed ord(<str>) Unicode character to
characters integer
s.rstrip(chars=None) Strip whitespace from s.isdecimal() True if [0-9], [०-९]
right end, or passed or [٩-٠]
characters
s.isdigit() True if isdecimal()
s.ljust(width, Left justify with or [²³¹…]
fillchar=' ') fillchar
s.isnumeric() True if isdigit() or
s.rjust(width, Right justify with [¼½¾零〇一…]
fillchar=' ') fillchar
s.isalnum() True if isnumeric()
s.center(width, Center with fillchar or [a-zA-Z…]
fillchar=' ')
s.isprintable() True if isalnum() or
s.split(sep=None, Split on whitespace, [ !#$%…]
maxsplit=-1) or sep str at most
maxsplit times s.isspace() True if [
\t\n\r\f\v\x1c-
s.splitlines(keepends Split lines on \x1f\x85\xa0…]
=False) [\n\r\f\v\x1c-
\x1e\x85\u2028\u2029] head, sep, tail = Search for separator
and \r\n s.partition(<separato from start and split
r>)
<separator>.join(<str Join sequence of
ings>) strings with head, sep, tail = Search for separator
separator string s.rpartition(<separat from end and split
or>)
s.find(<substring>) Index of first match
or -1 s.removeprefix(<prefi Remove prefix if
x>) 3.9+ present
s.index(<substring>) Index of first match
or raise ValueError s.removesuffix(<suffi Remove suffix if
x>) 3.9+ present
String escape
Sequence Escape
Literal backslash \\
Single quote \'
Double quote \"
Backspace \b
Carriage return \r

18 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

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

Python 3.8+ | 2024 Jul 16 © kieranholland.com 19 of 26


The *Best Python Cheat Sheet

>>> 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-consumptive
*?, +?, ?? Same as *, + and ?, as few as (?<=…) Match preceding, positive
possible lookbehind assertion
{m,n} m to n repetitions (?<!…) Non-match preceding, negative
{m,n}? m to n repetitions, as few as lookbehind assertion
possible (? Conditional match - A if group
[…] Character set: e.g. '[a-zA-Z]' (group)A|B previously matched else B
[^…] NOT character set )
\ Escape chars '*?+&$|()', (?letters) Set flags for RE ('i','L', 'm',
introduce special sequences 's', 'u', 'x')
\\ Literal '\' (?#…) Comment (ignored)

Regex special sequences


\<n> Match by integer group reference \s Whitespace [ \t\n\r\f\v] (see
starting from 1 flag: ASCII)
\A Start of string \S Non-whitespace (see flag: ASCII)
\b Word boundary (see flag: \w Alphanumeric (see flag:
ASCII|LOCALE) ASCII|LOCALE)
\B Not word boundary (see flag: \W Non-alphanumeric (see flag:
ASCII|LOCALE) 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)).

20 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


The *Best Python Cheat Sheet

(?a) | A | ASCII ASCII-only match for (?m) | M | MULTILINE Match every new line,
\w, \W, \b, \B, \d, not only start/end of
\D, \s, \S (default string
is Unicode) (?s) | S | DOTALL '.' matches ALL
(?i) | I | IGNORECASE Case insensitive chars, including
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 Obj string) matches as list of
escape(string) Escape non- groups or tuples (>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
is function, called
split(pattern, Splits by pattern, with a MatchObj
string[, maxsplit=0]) keeping splitter if
grouped subn(pattern, repl, Like sub(), but
string[, count=0]) returns (newString,
numberOfSubsMade)
Regex object
flags Flags split(string[, See split() function
groupindex {group name: group maxsplit=0])
number} findall(string[, See findall()
pattern Pattern pos[, endpos]]) function
match(string[, pos][, Match from start of finditer(string[, See finditer()
endpos]) target[pos:endpos] pos[, endpos]]) function
search(string[, pos] Match anywhere in sub(repl, string[, See sub() function
[, endpos]) target[pos:endpos] count=0])
subn(repl, string[, See subn() function
count=0])
Regex match object
pos pos passed to search or match re RE object
endpos endpos passed to search or
match

Python 3.8+ | 2024 Jul 16 © kieranholland.com 21 of 26


The *Best Python Cheat Sheet

group([g1, One or more groups of match span(group) (start(group), end(group));


g2, ...]) One arg, result is a string (None, None) if group didn't
Multiple args, result is tuple contibute
If gi is 0, returns the entire string String passed to match() or
matching string search()
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
start(group) Indices of start & end of
, end(group) group match (None if group
exists but didn't contribute)

Number
bool([object]) Boolean, see __bool__
True, False special method
int([float|str|bool]) Integer, see __int__ special method
5
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
Also see built-in functions abs, pow, round, sum, min, max.

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


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

Statistics

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

22 of 26 © kieranholland.com Python 3.8+ | 2024 Jul 16


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

Python 3.8+ | 2024 Jul 16 © 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 Python 3.8+ | 2024 Jul 16


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

Python 3.8+ | 2024 Jul 16 © 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 libraries PYTHONWARNINGS Set warning level
PYTHONPATH Augment default search [default/error/always/mod
path for module files ule/once/ignore] (-W)
PYTHONSTARTUP Module to execute before PYTHONPROFILEIMP Show module import times
entering interactive ORTTIME (-X)
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 Python 3.8+ | 2024 Jul 16

You might also like