kuniga.me > Docs > Python Cheatsheet
Syntax for common tasks I run into often. Assumes Python 3.
from enum import Enum
class MyEnum(Enum):
A = 'a'
B = 'b'
print(MyEnum('a')) # MyEnum.A
It does validation:
print(MyEnum('c'))
print(MyEnum.A.value) # 'a'
xs = [1, 2, 3]
ys = [f(x) for x in xs]
xs = [1, 2, 3]
ys = [x for x in xs if x % 2 == 0]
NOTE: filter and map can be combined into one.
Find if any (all) element satisfy a predicate:
xs = [1, 2, 3]
ys = any(predicate(x) for x in xs)
NOTE: this is a generator, so it will short-circuit once if finds an element satisfying the predicate. The version below creates a list first, so no short-circuit happens.
xs = [1, 2, 3]
ys = [any(predicate(x) for x in xs)]
Using default sorting:
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
Sorting using key function. For example, sort list of pairs by the second element:
sorted([[1, 3], [2, 2], [3, 1]], key=lambda x: x[1])
Sorting by custom comparator:
import functools
# Function that returns
# < 0 if a < b
# > 0 if a > b
# = 0 if a = b
def cmp(a, b):
return a - b
sorted([3, 2, 1], key=functools.cmp_to_key(cmp))
del dict[key]
ys = {k: f(v) for k, v in xs.items()}
Dictionaries are unordered sets, so you likely want to work with a list after sorting.
d = {'a': 3, 'b': 2}
xs = sorted(d.items(), key=lambda x: x[1])
s = {1, 2, 3}
Empty:
s = set()
Note that s = {}
creates an empty dictionary.
Add/insert
s.add(4)
s1 = set([1, 2])
s2 = set([2, 3])
s1 = s1 - s2 # {1}
s1 = set([1, 2])
s2 = set([2, 3])
s1 = s1.union(s2) # {1, 2, 3}
xs = {1, 2, 3}
ys = {f(x) for x in xs}
Basic Syntax:
class C:
def __init__(self, param):
self.param
def method(self):
return self.param
@staticmethod
def static_method():
return 1
Check if object is instance of a class:
class MyClass:
pass
x = MyClass()
isinstance(x, MyClass)
Methods where the bound variable is an instance to the class.
class C:
@classmethod
def class_method(cls):
print(cls) # __main__.C
def method(self):
print(self) # <__main__.C instance at 0x12345>;
See also: Class Methods in Revisiting Python: Object Oriented Programming
Lightweight syntax for creating classes / records.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
print(p.x) # 10
q = Point(y=10, x=20)
print(q.x) # 20
Complex types:
# ... continued from above
@dataclass
class Polygon:
pts: [Point]
pol = Polygon([p, q])
print(pol.pts) # [Point(x=10, y=20), Point(x=20, y=10)]
dataclasses.replace
:
p = Point(1, 2)
p_copy = dataclasses.replace(p)
Prevents fields from being changed:
@dataclass(frozen=True)
class Wrapper:
v: str = 'abc'
def __init__(self):
self.v = 'cde' # error
w = Wrapper()
w.v = 'cde' # error
It’s possible to bypass though:
@dataclass(frozen=True)
class Wrapper:
v: str = 'abc'
def __init__(self):
# internal backdoor
object.__setattr__(self, "v", "backdoor")
w = Wrapper()
# external backdoor
object.__setattr__(w, "foo", 'backdoor')
Basic syntax:
try:
raise Exception('hello')
except Exception as ex:
print('caught', str(ex))
Custom exception:
class MyException(Exception):
pass
try:
raise MyException('hello')
except MyException as ex:
print('caught specific', str(ex))
Re-raise exception
try:
raise Exception('hello')
except Exception as ex:
print('caught specific', str(ex))
raise
Raise new exception but preserve original stack trace:
try:
raise Exception('hello')
except Exception as ex:
raise Exception('new title') from ex
with open(filename, "r") as file:
print(file.readlines())
Temporary file:
# Note: file gets deleted once it exits the scope
tempfile.NamedTemporaryFile() as file:
file.write("Hello World\n")
# make sure to flush if something will read from it
file.flush()
read_my_file(file.name)
A decorator is basically a function transformer. Basic template:
import functools
def my_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
# pre-process
...
r = f(*args, **kwargs)
# post-process
...
return r
return wrapper
@my_decorator
def my_func():
pass
Current time:
datetime.now()
Adding/subtracting time:
datetime.now() + datetime.timedelta(days=1)
Wall-clock time in seconds:
start = time.time()
call()
elapsed_secs = time.time() - start
The Queue
class is an advanced implementation that can be used for example in multi-thread applications. We can still use it as a plain queue data structure.
from queue import Queue
# Create
q = Queue()
# Insert back
q.put(item)
# Retrieve and remove front
first = q.get()
# Front element without removing
first = q[0]
# Size
len(q)
# Is empty?
q.empty()