#Contents
ToC = {
'1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
'2. Types': [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
'3. Syntax': [Args, Inline, Imports, Decorator, Class, Duck_Type, Enum, Exception],
'4. System': [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
'5. Data': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
'6. Advanced': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
'7. Libraries': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
NumPy, Image, Audio, Games, Data]
}
#Main
if __name__ == '__main__':
main()
#List
= []
.append()
.extend()
.sort()
.reverse()
= sorted()
= reversed()
sum_of_elements = sum()
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(, key=lambda el: el[1])
sorted_by_both = sorted(, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable())
product_of_elems = functools.reduce(lambda out, el: out * el, )
list_of_chars = list()
- For details about sorted(), min() and max() see sortable.
- Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
.insert(, )
= .pop([])
= .count()
= .index()
.remove()
.clear()
#Dictionary
= .keys()
= .values()
= .items()
value = .get(key, default=None)
value = .setdefault(key, default=None)
= collections.defaultdict()
= collections.defaultdict(lambda: 1)
= dict()
= dict(zip(keys, values))
= dict.fromkeys(keys [, value])
.update()
value = .pop(key)
{k for k, v in .items() if v == value}
{k: v for k, v in .items() if k in keys}
Counter
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
.add()
.update( [, ...])
= .union()
= .intersection()
= .difference()
= .symmetric_difference()
= .issubset()
= .issuperset()
= .pop()
.remove()
.discard()
Frozen Set
- Is immutable and hashable.
- That means it can be used as a key in a dictionary or as an element in a set.
= frozenset()
#Tuple
Tuple is an immutable and hashable list.
Featured Content Ads
add advertising here = ()
= (,)
= (, [, ...])
Named Tuple
Tuple’s subclass with named elements.
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields
('x', 'y')
#Range
= range(to_exclusive)
= range(from_inclusive, to_exclusive)
= range(from_inclusive, to_exclusive, ±step_size)
from_inclusive = .start
to_exclusive = .stop
#Enumerate
for i, el in enumerate( [, i_start]):
...
#Iterator
= iter()
= iter(, to_exclusive)
= next( [, default])
= list()
Itertools
from itertools import count, repeat, cycle, chain, islice
= count(start=0, step=1)
= repeat( [, times])
= cycle()
= chain(, [, ...])
= chain.from_iterable()
= islice(, to_exclusive)
= islice(, from_inclusive, …)
#Generator
- Any function that contains a yield statement returns a generator.
- Generators and iterators are interchangeable.
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
#Type
- Everything is an object.
- Every object has a type.
- Type and class are synonymous.
= type()
= isinstance(, )
>>> 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, ModuleType
Abstract Base Classes
Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().
>>> from collections.abc import Sequence, Collection, Iterable
>>> isinstance([1, 2, 3], Iterable)
True
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ Sequence │ Collection │ Iterable ┃
┠──────────────────┼────────────┼────────────┼────────────┨
┃ list, range, str │ ✓ │ ✓ │ ✓ ┃
┃ dict, set │ │ ✓ │ ✓ ┃
┃ iter │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
>>> from numbers import Integral, Rational, Real, Complex, Number
>>> isinstance(123, Number)
True
┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┃ │ Integral │ Rational │ Real │ Complex │ Number ┃
┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ float │ │ │ ✓ │ ✓ │ ✓ ┃
┃ complex │ │ │ │ ✓ │ ✓ ┃
┃ decimal.Decimal │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
#String
= .strip()
= .strip('' )
= .split()
= .split(sep=None, maxsplit=-1)
= .splitlines(keepends=False)
= .join()
= in
= .startswith()
= .endswith()
= .find()
= .index()
= .replace(old, new [, count])
= .translate()
= chr()
= ord()
- Also:
'lstrip()'
, 'rstrip()'
and 'rsplit()'
.
- Also:
'lower()'
, 'upper()'
, 'capitalize()'
and 'title()'
.
Property Methods
┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┃ │ [ !#$%…] │ [a-zA-Z] │ [¼½¾] │ [²³¹] │ [0-9] ┃
┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃
┃ isdigit() │ │ │ │ ✓ │ ✓ ┃
┃ isdecimal() │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
- Also:
'isspace()'
checks for '[ tnrfvx1c-x1fx85…]'
.
#Regex
import re
= re.sub(, new, text, count=0)
= re.findall(, text)
= re.split(, text, maxsplit=0)
= re.search(, text)
= re.match(, text)
= re.finditer(, text)
- Search() and match() return None if they can’t find a match.
- Argument
'flags=re.IGNORECASE'
can be used with all functions.
- Argument
'flags=re.MULTILINE'
makes '^'
and '$'
match the start/end of each line.
- Argument
'flags=re.DOTALL'
makes dot also accept the 'n'
.
- Use
r'1'
or '\1'
for backreference.
- Add
'?'
after an operator to make it non-greedy.
Special Sequences
- By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless
'flags=re.ASCII'
argument is used.
- As shown below, it restricts special sequence matches to the first 128 characters and prevents
's'
from accepting '[x1c-x1f]'
(the so-called separator characters).
- Use a capital letter for negation.
'd' == '[0-9]'
'w' == '[a-zA-Z0-9_]'
's' == '[ tnrfv]'
#Format
= f'{} , {} '
= '{}, {}'.format(, )
Attributes
>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'
'187'
>>> '{p.height}'.format(p=person)
'187'
General Options
{:<10}
{:^10}
{:>10}
{:.<10}
{:0}
- Options can be generated dynamically:
f'{:{} […]}'
.
- Adding
'!r'
before the colon converts object to string by calling its repr() method.
Strings
{'abcde':10}
{'abcde':10.3}
{'abcde':.3}
{'abcde'!r:10}
Numbers
{123456:10}
{123456:10,}
{123456:10_}
{123456:+10}
{123456:=+10}
{123456: }
{-123456: }
Floats
{1.23456:10.3}
{1.23456:10.3f}
{1.23456:10.3e}
{1.23456:10.3%}
Comparison of presentation types:
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┃ │ {} │ {:f} │ {:e} │ {:%} ┃
┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
┃ 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%' ┃
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┃ │ {:.2} │ {:.2f} │ {:.2e} │ {:.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%' ┃
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
- When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes
'{6.5:.0f}'
a '6'
and '{7.5:.0f}'
an '8'
.
#Numbers
Types
= int()
= float()
= complex(real=0, imag=0)
= fractions.Fraction(0, 1)
= decimal.Decimal()
'int()'
and 'float()'
raise ValueError on malformed strings.
- Decimal numbers can be represented exactly, unlike floats where
'1.1 + 2.2 != 3.3'
.
- Precision of decimal operations is set with:
'decimal.getcontext().prec = '
.
Basic Functions
= pow(, )
= abs()
= round( [, ±ndigits])
Math
from math import e, pi, inf, nan, isinf, isnan
from math import sin, cos, tan, asin, acos, atan, degrees, radians
from math import log, log10, log2
Statistics
from statistics import mean, median, variance, stdev, pvariance, pstdev
Random
from random import random, randint, choice, shuffle, gauss, seed
= random()
= randint(from_inc, to_inc)
= choice()
Bin, Hex
= ±0b
= int('±' , 2)
= int('±0b' , 0)
= bin()
Bitwise Operators
= &
= |
= ^
= << n_bits
= ~
#Combinatorics
- Every function returns an iterator.
- If you want to print the iterator, you need to pass it to the list() function first!
from itertools import product, combinations, combinations_with_replacement, permutations
>>> product([0, 1], repeat=3)
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), ..., (1, 1, 1)]
>>> product('abc', 'abc')
[('a', 'a'), ('a', 'b'), ('a', 'c'),
('b', 'a'), ('b', 'b'), ('b', 'c'),
('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> combinations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'c')]
>>> combinations_with_replacement('abc', 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'),
('b', 'b'), ('b', 'c'),
('c', 'c')]
>>> permutations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'a'), ('b', 'c'),
('c', 'a'), ('c', 'b')]
#Datetime
- Module ‘datetime’ provides ‘date’
, ‘time’
, ‘datetime’
and ‘timedelta’ classes. All are immutable and hashable.
- Time and datetime objects can be ‘aware’
, meaning they have defined timezone, or ‘naive’
, meaning they don’t.
- If object is naive, it is presumed to be in the system’s timezone.
from datetime import date, time, datetime, timedelta
from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary
Constructors
= date(year, month, day)
= time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
- = datetime(year, month, day, hour=0, minute=0, second=0, ...)
= timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, ...)
- Use
'.weekday()'
to get the day of the week (Mon == 0).
'fold=1'
means the second pass in case of time jumping back for one hour.
- TD converts and normalizes args to ±days, seconds (< 86 400) and microseconds (< 1M).
Now
= D/DT.today()
= DT.utcnow()
= DT.now()
- To extract time use
'.time()'
, '.time()'
or '.timetz()'
.
Timezone
= UTC
= tzlocal()
= gettz('/' )
= - .astimezone(
)
= .replace(tzinfo=)
Encode
= D/T/DT.fromisoformat('' )
- = DT.strptime(
, '' )
= D/DT.fromordinal()
= DT.fromtimestamp()
= DT.fromtimestamp(, )
- ISO strings come in following forms:
'YYYY-MM-DD'
, 'HH:MM:SS.ffffff[±]'
, or both separated by an arbitrary character. Offset is formatted as: 'HH:MM'
.
- Epoch on Unix systems is:
'1970-01-01 00:00 UTC'
, '1970-01-01 01:00 CET'
, …
Decode
= .isoformat(sep='T')
= .strftime('' )
= .toordinal()
= .timestamp()
= .timestamp()
Format
>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
>>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z")
"Thursday, 14th of May '15, 11:39PM UTC+02:00"
'%Z'
only accepts 'UTC/GMT'
and local timezone’s code. '%z'
also accepts '±HH:MM'
.
- For abbreviated weekday and month use
'%a'
and '%b'
.
Arithmetics
= ±
= -
= -
= *
= /
#Arguments
Inside Function Call
()
()
(, )
Inside Function Definition
def f() :
def f() :
def f(, ) :
#Splat Operator
Inside Function Call
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)
Is the same as:
func(1, 2, x=3, y=4, z=5)
Inside Function Definition
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
Featured Content Ads
add advertising here
def add(*a):
return sum(a)
>>> add(1, 2, 3)
6
Legal argument combinations:
def f(x, y, z):
def f(*, x, y, z):
def f(x, *, y, z):
def f(x, y, *, z):
def f(*args):
def f(x, *args):
def f(*args, z):
def f(x, *args, z):
def f(**kwargs):
def f(x, **kwargs):
def f(*, x, **kwargs):
def f(*args, **kwargs):
def f(x, *args, **kwargs):
def f(*args, y, **kwargs):
def f(x, *args, z, **kwargs):
Other Uses
= [* [, ...]]
= {* [, ...]}
= (*, [...])
= {** [, ...]}
head, *body, tail =
#Inline
Lambda
= lambda:
= lambda , :
Comprehensions
= [i+1 for i in range(10)]
= {i for i in range(10) if i > 5}
= (i+5 for i in range(10))
= {i: i*2 for i in range(10)}
>>> [l+r for l in 'abc' for r in 'abc']
['aa', 'ab', 'ac', ..., 'cc']
Map, Filter, Reduce
= map(lambda x: x + 1, range(10))
= filter(lambda x: x > 5, range(10))
= reduce(lambda out, x: out + x, range(10))
- Reduce must be imported from the functools module.
Any, All
= any()
= all()
Conditional Expression
= if else
>>> [a if a else 'zero' for a in (0, 1, 2, 3)]
['zero', 1, 2, 3]
Named Tuple, Enum, Dataclass
from collections import namedtuple
Point = namedtuple('Point', 'x y')
point = Point(0, 0)
from enum import Enum
Direction = Enum('Direction', 'n e s w')
direction = Direction.n
from dataclasses import make_dataclass
Creature = make_dataclass('Creature', ['loc', 'dir'])
creature = Creature(point, direction)
#Imports
import
import
import .
- Package is a collection of modules, but it can also define its own objects.
- On a filesystem this corresponds to a directory of Python files with an optional init script.
- Running
'import '
does not automatically provide access to the package’s modules unless they are explicitly imported in its init script.
#Closure
We have/get a closure in Python when:
- A nested function references a value of its enclosing function and then
- the enclosing function returns the nested function.
def get_multiplier(a):
def out(b):
return a * b
return out
>>> multiply_by_3 = get_multiplier(3)
>>> multiply_by_3(10)
30
- If multiple nested functions within enclosing function reference the same value, that value gets shared.
- To dynamically access function’s first free variable use
'.__closure__[0].cell_contents'
.
Partial
from functools import partial
= partial( [, , , ...])
>>> import operator as op
>>> multiply_by_3 = partial(op.mul, 3)
>>> multiply_by_3(10)
30
- Partial is also useful in cases when function needs to be passed as an argument because it enables us to set its arguments beforehand.
- A few examples being:
'defaultdict()'
, 'iter(, to_exclusive)'
and dataclass’s 'field(default_factory=)'
.
Non-Local
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a ‘global’ or a ‘nonlocal’.
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 function_that_gets_passed_to_decorator():
...
Debugger Example
Decorator that prints function’s name every time it gets called.
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
- Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).
- Without it
'add.__name__'
would return 'out'
.
LRU Cache
Decorator that caches function’s return values. All function’s arguments must be hashable.
Featured Content Ads
add advertising here
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
- CPython interpreter limits recursion depth to 1000 by default. To increase it use
'sys.setrecursionlimit()'
.
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
from functools import wraps
def debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
result = func(*args, **kwargs)
print(func.__name__, result if print_result else '')
return result
return out
return decorator
@debug(print_result=True)
def add(x, y):
return x + y
#Class
class <name>:
def __init__(self, a):
self.a = a
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
def __str__(self):
return str(self.a)
@classmethod
def get_class_name(cls):
return cls.__name__
- Return value of repr() should be unambiguous and of str() readable.
- If only repr() is defined, it will also be used for str().
Str() use cases:
print()
print(f'{} ')
raise Exception()
csv.writer().writerow([])
logging.warning()
Repr() use cases:
print([])
print(f'{!r} ')
>>>
Z = dataclasses.make_dataclass('Z', ['a']); print(Z())
Constructor Overloading
class <name>:
def __init__(self, a=None):
self.a = a
Inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
Multiple Inheritance
class A: pass
class B: pass
class C(A, B): pass
MRO determines the order in which parent classes are traversed when searching for a method:
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
Property
Pythonic way of implementing getters and setters.
class MyClass:
@property
def a(self):
return self._a
@a.setter
def a(self, value):
self._a = value
>>> obj = MyClass()
>>> obj.a = 123
>>> obj.a
123
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
from dataclasses import dataclass, field
@dataclass(order=False, frozen=False)
class <class_name>:
:
: =
: list/dict/set = field(default_factory=list/dict/set)
- Objects can be made sortable with
'order=True'
and immutable with 'frozen=True'
.
- For object to be hashable, all attributes must be hashable and frozen must be True.
- Function field() is needed because
': list = []'
would make a list that is shared among all instances. Its ‘default_factory’ argument can be any callable.
- For attributes of arbitrary type use
'typing.Any'
.
Inline:
from dataclasses import make_dataclass
= make_dataclass('' , )
= make_dataclass('' , )
= ('' , [, ])
Slots
Mechanism that restricts objects to attributes listed in ‘slots’ and significantly reduces their memory footprint.
class MyClassWithSlots:
__slots__ = ['a']
def __init__(self):
self.a = 1
Copy
from copy import copy, deepcopy
#Duck Types
A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.
Comparable
- If eq() method is not overridden, it returns
'id(self) == id(other)'
, which is the same as 'self is other'
.
- That means all objects compare not equal by default.
- Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.
- Ne() 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 both hash() and eq() methods and its hash value should never change.
- Hashable objects that compare equal must have the same hash value, meaning default hash() that returns
'id(self)'
will not do.
- That is why Python automatically makes classes unhashable if you only implement eq().
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 and the rest will be automatically generated.
- Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn’t arise in other contexts.
- When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.
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 methods next() and iter() is an iterator.
- Next() should return next item or raise StopIteration.
- Iter() should return ‘self’.
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 and set_iterator.
- Objects returned by the itertools module, such as count, repeat and cycle.
- Generators returned by the generator functions and generator expressions.
- File objects returned by the open() function, etc.
Callable
- All functions and classes have a call() method, hence are callable.
- When this cheatsheet uses
''
as an argument, it actually means ''
.
class Counter:
def __init__(self):
self.i = 0
def __call__(self):
self.i += 1
return self.i
>>> counter = Counter()
>>> counter(), counter(), counter()
(1, 2, 3)
Context Manager
- Enter() should lock the resources and optionally return an object.
- Exit() should release the resources.
- Any exception that happens inside the with block is passed to the exit() method.
- If it wishes to suppress the exception it must return a true value.
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 method is iter(). It should return an iterator of object’s items.
- 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().
- This cheatsheet actually means
''
when it uses ''
.
- I chose not to use the name ‘iterable’ because it sounds scarier and more vague than ‘collection’. The only drawback of this decision is that a reader could think a certain function doesn’t accept iterators when it does, since iterators are the only iterable objects that 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.
- Iter() and contains() automatically work on any object that has getitem() defined.
- Reversed() automatically works on any object that has len() and getitem() defined.
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)
ABC Sequence
- It’s a richer interface than the basic sequence.
- Extending it generates iter(), contains(), reversed(), index() and count().
- Unlike
'abc.Iterable'
and 'abc.Collection'
, it is not a duck type. That is why 'issubclass(MySequence, abc.Sequence)'
would return False even if MySequence had all the methods defined.
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]
Table of required and automatically available special methods:
┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃
┠────────────┼────────────┼────────────┼────────────┼──────────────┨
┃ iter() │ ! │ ! │ ✓ │ ✓ ┃
┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ len() │ │ ! │ ! │ ! ┃
┃ getitem() │ │ │ ! │ ! ┃
┃ reversed() │ │ │ ✓ │ ✓ ┃
┃ index() │ │ │ │ ✓ ┃
┃ count() │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
- Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.
- Names of their required methods are stored in
'.__abstractmethods__'
.
#Enum
from enum import Enum, auto
class <enum_name>(Enum):
=
= ,
= auto()
- If there are no numeric values before auto(), it returns 1.
- Otherwise it returns an increment of the last numeric value.
= .
= ['' ]
= ()
= .name
= .value
list_of_members = list()
member_names = [a.name for a in ]
member_values = [a.value for a in ]
random_member = random.choice(list())
def get_next_member(member):
members = list(member.__class__)
index = (members.index(member) + 1) % len(members)
return members[index]
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:
from functools import partial
LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
'OR': partial(lambda l, r: l or r)})
- Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.
#Exceptions
Basic Example
try:
except :
Complex Example
try:
except :
except :
else:
finally:
- 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).
Catching Exceptions
except :
except as :
except (, [...]):
except (, [...]) as :
- Also catches subclasses of the exception.
- Use
'traceback.print_exc()'
to print the error message to stderr.
- Use
'print()'
to print just the cause of the exception (its arguments).
Raising Exceptions
raise
raise ()
raise ( [, ...])
Re-raising caught exception:
except as :
...
raise
Exception Object
arguments = .args
exc_type = .__class__
filename = .__traceback__.tb_frame.f_code.co_filename
func_name = .__traceback__.tb_frame.f_code.co_name
line = linecache.getline(filename, .__traceback__.tb_lineno)
error_msg = ''.join(traceback.format_exception(exc_type, , .__traceback__))
Built-in Exceptions
BaseException
├── SystemExit
├── KeyboardInterrupt
└── Exception
├── ArithmeticError
│ └── ZeroDivisionError
├── AttributeError
├── EOFError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── NameError
├── OSError
│ └── FileNotFoundError
├── RuntimeError
│ └── RecursionError
├── StopIteration
├── TypeError
└── ValueError
└── UnicodeError
Collections and their exceptions:
┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ List │ Set │ Dict ┃
┠───────────┼────────────┼────────────┼────────────┨
┃ getitem() │ IndexError │ │ KeyError ┃
┃ pop() │ IndexError │ KeyError │ KeyError ┃
┃ remove() │ ValueError │ KeyError │ ┃
┃ index() │ ValueError │ │ ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
Useful built-in exceptions:
raise TypeError('Argument is of wrong type!')
raise ValueError('Argument is of right type but inappropriate value!')
raise RuntimeError('None of above!')
User-defined Exceptions
class MyError(Exception):
pass
class MyInputError(MyError):
pass
#Exit
Exits the interpreter by raising SystemExit exception.
import sys
sys.exit()
sys.exit()
sys.exit()
#Print
print(, ..., sep=' ', end='n', file=sys.stdout, flush=False)
- Use
'file=sys.stderr'
for messages about errors.
- Use
'flush=True'
to forcibly flush the stream.
Pretty Print
from pprint import pprint
pprint(, width=80, depth=None, compact=False, sort_dicts=True)
- Levels deeper than 'depth' get replaced by '…'.
- Trailing newline gets stripped.
- Prompt string is printed to the standard output before reading input.
- Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.
#Command Line Arguments
import sys
scripts_path = sys.argv[0]
arguments = sys.argv[1:]
Argument Parser
from argparse import ArgumentParser, FileType
p = ArgumentParser(description=)
p.add_argument('-' , '--' , action='store_true')
p.add_argument('-' , '--' , type=)
p.add_argument('' , type=, nargs=1)
p.add_argument('' , type=, nargs='+')
p.add_argument('' , type=, nargs='*')
args = p.parse_args()
value = args.
- Use
'help='
to set argument description.
- Use
'default='
to set the default value.
- Use
'type=FileType()'
for files.
#Open
Opens the file and returns a corresponding file object.
= open(, mode='r', encoding=None, newline=None)
'encoding=None'
means that the default encoding is used, which is platform dependent. Best practice is to use 'encoding="utf-8"'
whenever possible.
'newline=None'
means all different end of line combinations are converted to 'n' on read, while on write all 'n' characters are converted to system's default line separator.
'newline=""'
means no conversions take place, but input is still broken into chunks by readline() and readlines() on either 'n', 'r' or 'rn'.
Modes
'r'
- Read (default).
'w'
- Write (truncate).
'x'
- Write or fail if the file already exists.
'a'
- Append.
'w+'
- Read and write (truncate).
'r+'
- Read and write from the start.
'a+'
- Read and write from the end.
't'
- Text mode (default).
'b'
- Binary mode.
Exceptions
'FileNotFoundError'
can be raised when reading with 'r'
or 'r+'
.
'FileExistsError'
can be raised when writing with 'x'
.
'IsADirectoryError'
and 'PermissionError'
can be raised by any.
'OSError'
is the parent class of all listed exceptions.
File Object
.seek(0)
.seek(offset)
.seek(0, 2)
.seek(±offset, )
= .read(size=-1)
= .readline()
= .readlines()
= next()
.write()
.writelines()
.flush()
- Methods do not add or strip trailing newlines, even writelines().
Read Text from File
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
Write Text to File
def write_to_file(filename, text):
with open(filename, 'w', encoding='utf-8') as file:
file.write(text)
#Paths
from os import getcwd, path, listdir
from glob import glob
= getcwd()
= path.join(, ...)
= path.abspath()
= path.basename()
= path.dirname()
= path.splitext()
= listdir(path='.')
= glob('' )
= path.exists()
= path.isfile()
= path.isdir()
DirEntry
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.
from os import scandir
= scandir(path='.')
= .path
= .name
= open()
Path Object
from pathlib import Path
= Path( [, ...])
= / [/ ...]
= Path()
= Path.cwd()
= Path.home()
= Path(__file__).resolve()
= .parent
= .name
= .stem
= .suffix
= .parts
= .iterdir()
= .glob('' )
= str()
= open()
#OS Commands
Files and Directories
- Paths can be either strings, Paths or DirEntry objects.
- Functions report OS related errors by raising either OSError or one of its subclasses.
import os, shutil
os.chdir()
os.mkdir(, mode=0o777)
os.makedirs(, mode=0o777)
shutil.copy(from, to)
shutil.copytree(from, to)
os.rename(from, to)
os.replace(from, to)
os.remove()
os.rmdir()
shutil.rmtree()
Shell Commands
import os
= os.popen('' ).read()
Sends '1 + 1' to the basic calculator and captures its output:
>>> from subprocess import run
>>> run('bc', input='1 + 1n', capture_output=True, text=True)
CompletedProcess(args='bc', returncode=0, stdout='2n', stderr='')
Sends test.in to the basic calculator running in standard mode and saves its output to test.out:
>>> from shlex import split
>>> os.popen('echo 1 + 1 > test.in')
>>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
CompletedProcess(args=['bc', '-s'], returncode=0)
>>> open('test.out').read()
'2n'
#JSON
Text file format for storing collections of strings and numbers.
import json
= json.dumps(, ensure_ascii=True, indent=None)
= json.loads()
Read Object from JSON File
def read_json_file(filename):
with open(filename, encoding='utf-8') as file:
return json.load(file)
Write Object to JSON File
def write_to_json_file(filename, an_object):
with open(filename, 'w', encoding='utf-8') as file:
json.dump(an_object, file, ensure_ascii=False, indent=2)
Read Object from File
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
Write Object to File
def write_to_pickle_file(filename, an_object):
with open(filename, 'wb') as file:
pickle.dump(an_object, file)
Read
= csv.reader()
= next()
= list()
- File must be opened with a
'newline=""'
argument, or newlines embedded inside quoted fields will not be interpreted correctly!
Write
= csv.writer()
.writerow()
.writerows()
- File must be opened with a
'newline=""'
argument, or 'r' will be added in front of every 'n' on platforms that use 'rn' line endings!
Parameters
'dialect'
- Master parameter that sets the default values.
'delimiter'
- A one-character string used to separate fields.
'quotechar'
- Character for quoting fields that contain special characters.
'doublequote'
- Whether quotechars inside fields get doubled or escaped.
'skipinitialspace'
- Whether whitespace after delimiter gets stripped.
'lineterminator'
- Specifies how writer terminates rows.
'quoting'
- Controls the amount of quoting: 0 - as necessary, 1 - all.
'escapechar'
- Character for escaping quotechars if doublequote is False.
Dialects
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ excel │ excel-tab │ unix ┃
┠──────────────────┼──────────────┼──────────────┼──────────────┨
┃ delimiter │ ',' │ 't' │ ',' ┃
┃ quotechar │ '"' │ '"' │ '"' ┃
┃ doublequote │ True │ True │ True ┃
┃ skipinitialspace │ False │ False │ False ┃
┃ lineterminator │ 'rn' │ 'rn' │ 'n' ┃
┃ quoting │ 0 │ 0 │ 1 ┃
┃ escapechar │ None │ None │ None ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
Read Rows from CSV File
def read_csv_file(filename):
with open(filename, encoding='utf-8', newline='') as file:
return list(csv.reader(file))
Write Rows to CSV File
def write_to_csv_file(filename, rows):
with open(filename, 'w', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
#SQLite
Server-less database engine that stores each database into a separate file.
Connect
Opens a connection to the database file. Creates a new file if path doesn't exist.
import sqlite3
= sqlite3.connect()
.close()
Read
Returned values can be of type str, int, float, bytes or None.
= .execute('' )
= .fetchone()
= .fetchall()
Write
.execute('' )
.commit()
.rollback()
Or:
with :
.execute('' )
Placeholders
- Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
- Bools will be stored and returned as ints and dates as ISO formatted strings.
.execute('' , )
.execute('' , )
.executemany('' , )
Example
In this example values are not actually saved because 'conn.commit()'
is omitted!
>>> conn = sqlite3.connect('test.db')
>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
>>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
1
>>> conn.execute('SELECT * FROM person').fetchall()
[(1, 'Jean-Luc', 187)]
MySQL
Has a very similar interface, with differences listed below.
from mysql import connector
= connector.connect(host=, …)
= .cursor()
.execute('' )
.execute('' , )
.execute('' , )
#Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.
= b''
= []
= []
= .join()
Encode
= bytes()
= bytes(, 'utf-8')
= .to_bytes(n_bytes, …)
= bytes.fromhex('' )
Decode
= list()
= str(, 'utf-8')
= int.from_bytes(, …)
'' = .hex()
Read Bytes from File
def read_bytes(filename):
with open(filename, 'rb') as file:
return file.read()
Write Bytes to File
def write_bytes(filename, bytes_obj):
with open(filename, 'wb') as file:
file.write(bytes_obj)
#Struct
- Module that performs conversions between a sequence of numbers and a bytes object.
- System’s type sizes and byte order are used by default.
from struct import pack, unpack, iter_unpack
= pack('' , [, , ...])
= unpack('' , )
= iter_unpack('' , )
Example
>>> pack('>hhl', 1, 2, 3)
b'x00x01x00x02x00x00x00x03'
>>> unpack('>hhl', b'x00x01x00x02x00x00x00x03')
(1, 2, 3)
Format
For standard type sizes start format string with:
'='
- system's byte order (usually little-endian)
'<'
- little-endian
'>'
- big-endian (also '!'
)
Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:
'x'
- pad byte
'b'
- char (1/1)
'h'
- short (2/2)
'i'
- int (2/4)
'l'
- long (4/4)
'q'
- long long (8/8)
Floating point types:
'f'
- float (4/4)
'd'
- double (8/8)
#Array
List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Sizes and byte order are always determined by the system.
from array import array
= array('' , )
= array('' , )
= array('' , )
= bytes()
.write()
#Memory View
- A sequence object that points to the memory of another object.
- Each element can reference a single or multiple consecutive bytes, depending on format.
- Order and number of elements can be changed with slicing.
- Casting only works between char and other types and uses system's sizes and byte order.
= memoryview()
= []
= []
= .cast('' )
.release()
Decode
= bytes()
= .join()
= array('' , )
.write()
= list()
= str(, 'utf-8')
= int.from_bytes(, …)
'' = .hex()
#Deque
A thread-safe list with efficient appends and pops from either side. Pronounced "deck".
from collections import deque
= deque(, maxlen=None)
.appendleft()
.extendleft()
= .popleft()
.rotate(n=1)
#Threading
- CPython interpreter can only run a single thread at a time.
- That is why using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.
from threading import Thread, RLock, Semaphore, Event, Barrier
from concurrent.futures import ThreadPoolExecutor
Thread
= Thread(target=)
.start()
= .is_alive()
.join()
- Use
'kwargs='
to pass keyword arguments to the function.
- Use
'daemon=True'
, or the program will not be able to exit while the thread is alive.
Lock
= RLock()
.acquire()
.release()
Semaphore, Event, Barrier
= Semaphore(value=1)
= Event()
= Barrier(n_times)
Thread Pool Executor
Object that manages thread execution.
= ThreadPoolExecutor(max_workers=None)
.shutdown(wait=True)
= .map(, , ...)
= .submit(, , ...)
= .done()
= .result()
Queue
A thread-safe FIFO queue. For LIFO queue use LifoQueue.
from queue import Queue
= Queue(maxsize=0)
.put()
.put_nowait()
= .get()
= .get_nowait()
#Operator
Module of functions that provide the functionality of operators.
from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, xor, inv
from operator import itemgetter, attrgetter, methodcaller
import operator as op
elementwise_sum = map(op.add, list_a, list_b)
sorted_by_second = sorted(, key=op.itemgetter(1))
sorted_by_both = sorted(, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, )
union_of_sets = functools.reduce(op.or_, )
last_element = op.methodcaller('pop')()
- Functions and_(), or_(), xor() and inv() correspond to operators '&', '|', '^' and '~'.
- They only work on objects with and(), or(), xor() and invert() special methods.
- Also:
' = &|^ '
and ' = &|^ '
.
Attributes
= dir()
= vars()
= hasattr(, '' )
value = getattr(, '' )
setattr(, '' , value)
delattr(, '' )
Parameters
from inspect import signature
= signature()
= .parameters
= .name
= .kind
Code that generates code.
Type
Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.
= type('' , , )
>>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
>>> z = Z()
Meta Class
A class that creates classes.
def my_meta_class(name, parents, attrs):
attrs['a'] = 'abcde'
return type(name, parents, attrs)
Or:
class MyMetaClass(type):
def __new__(cls, name, parents, attrs):
attrs['a'] = 'abcde'
return type.__new__(cls, name, parents, attrs)
- New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.
- It receives the same arguments as init(), except for the first one that specifies the desired type of the returned instance (MyMetaClass in our case).
- Like in our case, new() can also be called directly, usually from a new() method of a child class (
def __new__(cls): return super().__new__(cls)
).
- The only difference between the examples above is that my_meta_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.
Metaclass Attribute
Right before a class is created it checks if it has the 'metaclass' attribute defined. If no