09. Standard library power tools — Cheat sheet
The tools of module 09 on one page. Every runnable block on this page is checked against its output. All modules here ship with Python 3.12+; zoneinfo on Windows also needs the tzdata package.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| count items | Counter(iterable) |
Counter(categories).most_common(3) |
| add weighted counts | counter[key] += n |
units[product] += quantity |
| group records under a key | defaultdict(list) |
by_region[r["region"]].append(r) |
| sum per key | defaultdict(float) |
revenue[region] += value |
| collect unique values per key | defaultdict(set) |
orders[channel].add(order_id) |
| keep the last n values | deque(maxlen=n) |
window.append(reading) |
| a fast first-in, first-out queue | deque with append / popleft |
tasks.popleft() |
| a read-only record with field names | namedtuple |
Store("S01", "Chicago") |
| join iterables into one stream | chain(a, b), chain.from_iterable(xs) |
chain.from_iterable(files) |
| take items 10 to 19 of a stream | islice(it, 10, 20) |
islice(f, 3) for 3 lines |
| cut a stream into chunks | batched(it, n) |
batched(ids, 250) |
| running totals | accumulate(xs) |
accumulate(monthly) |
| a running maximum | accumulate(xs, max) |
accumulate(temps, max) |
| each item with the next | pairwise(xs) |
(b - a) / a per pair |
| groups of consecutive equal keys | groupby(sorted(xs, key=k), key=k) |
runs of warn readings |
| every combination of settings | product(a, b, c) |
a hyperparameter grid |
| every unordered pair | combinations(xs, 2) |
products bought together |
| fix some arguments | partial(func, x=1) |
partial(in_range, low=19, high=23) |
| fold a sequence into one value | reduce(func, xs, start) |
reduce(set.intersection, sets) |
| remember results of a pure function | @cache, @lru_cache(maxsize=n) |
a slow lookup |
| a key function for a field | itemgetter("k"), attrgetter("k") |
sorted(rows, key=itemgetter("revenue")) |
| parse an ISO date | date.fromisoformat(s) |
date.fromisoformat("2024-05-01") |
| parse any date layout | datetime.strptime(s, fmt) |
strptime("07/01/2023", "%d/%m/%Y") |
| format a date | d.strftime(fmt), d.isoformat(), f"{d:%Y-%m}" |
f"{day:%d %b}" |
| a duration | timedelta(days=, hours=, minutes=) |
start + 6 * timedelta(minutes=10) |
| an aware UTC timestamp | datetime(..., tzinfo=UTC), datetime.now(UTC) |
from datetime import UTC |
| convert to local time | dt.astimezone(ZoneInfo("America/Chicago")) |
for display only |
| find a pattern anywhere | re.search(p, s) |
re.search(r"(\d+)ms", line) |
| validate a whole value | re.fullmatch(p, s) |
re.fullmatch(r"P\d{3}", pid) |
| all matches | re.findall(p, s), re.finditer(p, s) |
re.findall(r"O\d{6}", text) |
| replace a pattern | re.sub(p, repl, s) |
re.sub(r"user=\S+", "user=***", s) |
| reuse a pattern | re.compile(p, flags) |
LINE = re.compile(r"...", re.VERBOSE) |
| mean, median, standard deviation | statistics.mean, median, stdev |
statistics.median(values) |
| percentiles | statistics.quantiles(xs, n=100) |
[94] is the 95th percentile |
| reproducible random numbers | rng = random.Random(42) |
rng.choices(xs, k=len(xs)) |
| read a setting | os.environ.get("NAME", "default") |
int(os.environ.get("N", "30")) |
| copy a file or folder | shutil.copy2, shutil.copytree |
copytree(src, dst, dirs_exist_ok=True) |
| zip a folder | shutil.make_archive(base, "zip", root_dir) |
returns the full archive path |
| run another program | subprocess.run([...], check=True) |
[sys.executable, "-c", code] |
Which tool for which job
Section titled “Which tool for which job”| Job | Standard library | pandas or NumPy equivalent (Part 4) | Choose the standard library when… |
|---|---|---|---|
| Count values | Counter |
s.value_counts() |
the data is a list or a stream, not a table |
| Group and aggregate | defaultdict(list or float) |
df.groupby(key).agg(...) |
a few thousand records, no table needed |
| Rolling window | deque(maxlen=n) |
s.rolling(n).mean() |
streaming data, one value at a time |
| Records | namedtuple |
a DataFrame row | small, read-only records |
| Combine sources | chain, chain.from_iterable |
pd.concat |
files too big to load at once |
| Chunks | batched, islice |
pd.read_csv(chunksize=n) |
sending rows to an API or database |
| Running totals | accumulate |
s.cumsum(), s.cummax() |
a short list |
| Changes between neighbors | pairwise |
s.pct_change(), s.diff() |
a short list |
| Runs of equal values | groupby (unsorted) |
(s != s.shift()).cumsum() |
detecting streaks in a stream |
| Grid of settings | product, combinations |
ParameterGrid (scikit-learn) |
a hand-written search |
| Caching | cache, lru_cache |
(none) | repeated slow calls with the same arguments |
| Dates | datetime, timedelta |
pd.to_datetime, .dt, pd.Timedelta |
parsing single values, scripts |
| Time zones | zoneinfo.ZoneInfo |
.dt.tz_localize, .dt.tz_convert |
any code; both use IANA names |
| Text patterns | re |
s.str.extract, s.str.replace(regex=True) |
logs and single strings |
| Summary statistics | statistics |
s.describe(), np.percentile |
a list of numbers, no dependencies |
| Random samples | random.Random(42) |
np.random.default_rng(42), df.sample(random_state=42) |
small simulations |
| Files and folders | shutil, pathlib |
(none) | automation |
| Other programs | subprocess |
(none) | running tools and checks |
collections
Section titled “collections”| Tool | Key operations | Notes |
|---|---|---|
Counter(iterable) |
c[k], c[k] += n, most_common(n), total(), update(it), +, -, &, | |
missing key → 0; - drops counts ≤ 0 |
defaultdict(factory) |
d[k] creates factory() when missing |
factories: list, set, float, int, dict, lambda: "n/a" |
deque(it, maxlen=n) |
append, appendleft, pop, popleft, extend, rotate(n), maxlen |
O(1) at both ends; indexing the middle is O(n) |
namedtuple(name, fields) |
.field, [i], unpacking, _replace(**kw), _asdict(), _fields, _make(it) |
immutable; typing.NamedTuple adds type hints (module 21) |
OrderedDict |
move_to_end(k), popitem(last=False) |
rarely needed: dicts keep insertion order since 3.7 |
ChainMap(a, b) |
lookups search a, then b |
layered settings: command line over environment over defaults |
from collections import ChainMap, Counter, defaultdict, deque, namedtuple
units = Counter({"P001": 12, "P014": 7}) + Counter({"P001": 3, "P025": 2})print(units.most_common(2), units.total())
by_store = defaultdict(list)for store, revenue in [("S01", 79.99), ("S02", 14.99), ("S01", 249.0)]: by_store[store].append(revenue)print({store: round(sum(v), 2) for store, v in by_store.items()})
last3 = deque([20.1, 20.4, 20.9, 21.3], maxlen=3) # keeps the last 3print(list(last3), round(sum(last3) / len(last3), 2))
Reading = namedtuple("Reading", "sensor_id temperature_c") # a string of names worksr = Reading("S1", 21.7)print(r, r._fields, r._replace(temperature_c=22.0).temperature_c)
settings = ChainMap({"top": 5}, {"top": 3, "by": "region"}) # first map winsprint(settings["top"], settings["by"])[('P001', 15), ('P014', 7)] 24{'S01': 328.99, 'S02': 14.99}[20.4, 20.9, 21.3] 20.87Reading(sensor_id='S1', temperature_c=21.7) ('sensor_id', 'temperature_c') 22.05 regionitertools
Section titled “itertools”| Function | Yields | Example → result |
|---|---|---|
chain(a, b) |
items of a, then b |
chain("ab", "c") → a b c |
chain.from_iterable(xs) |
items of each iterable in xs |
chain.from_iterable([[1], [2, 3]]) → 1 2 3 |
islice(it, stop) / (it, start, stop, step) |
a slice of any iterable | islice(range(10), 2, 8, 3) → 2 5 |
batched(it, n) (3.12+) |
tuples of n items; last may be short |
batched("abcde", 2) → ('a','b') ('c','d') ('e',) |
accumulate(it, func) |
running results (default +) |
accumulate([1, 2, 3]) → 1 3 6 |
pairwise(it) |
overlapping pairs | pairwise("abc") → ('a','b') ('b','c') |
groupby(it, key) |
(key, group) per run of equal keys |
groupby("aabca") → a b c a |
product(a, b, repeat=1) |
Cartesian product (every combination) | product("ab", [1, 2]) → 4 pairs |
combinations(it, r) |
unordered picks, no repeats | combinations("abc", 2) → ab ac bc |
combinations_with_replacement(it, r) |
unordered picks, repeats allowed | ("abc", 2) → 6 picks |
permutations(it, r) |
ordered picks | permutations("abc", 2) → 6 pairs |
zip_longest(a, b, fillvalue=None) |
like zip, pads the shorter one |
zip_longest("ab", "c") → ('a','c') ('b',None) |
starmap(func, pairs) |
func(*pair) for each pair |
starmap(pow, [(2, 3)]) → 8 |
takewhile(pred, it) / dropwhile(pred, it) |
items while / after pred is true |
takewhile(lambda x: x < 3, [1, 4, 2]) → 1 |
compress(data, flags) |
items whose flag is truthy | compress("abc", [1, 0, 1]) → a c |
filterfalse(pred, it) |
items where pred is false |
the opposite of filter |
count(start, step), cycle(it), repeat(x, n) |
infinite or repeated streams | pair with islice or zip |
tee(it, n) |
n independent copies of one iterator |
stores items in memory |
from itertools import ( accumulate, batched, chain, combinations, count, groupby, islice, pairwise, product, zip_longest,)
print(list(islice(count(1), 3)), list(batched(range(7), 3)))print(list(accumulate([3, 1, 4, 1, 5])), list(accumulate([3, 1, 4, 1, 5], max)))print([round(b / a - 1, 2) for a, b in pairwise([100, 120, 90])])print([(k, len(list(g))) for k, g in groupby("ooowwo")]) # runs, not totalsprint(len(list(product([0.01, 0.1], [3, 5], ["gini", "entropy"]))))print(list(combinations(["S01", "S02", "S03"], 2)))print(list(zip_longest(["a", "b", "c"], [1, 2], fillvalue=0)))print(list(chain.from_iterable([["P001"], ["P002", "P003"]])))[1, 2, 3] [(0, 1, 2), (3, 4, 5), (6,)][3, 4, 8, 9, 14] [3, 3, 4, 4, 5][0.2, -0.25][('o', 3), ('w', 2), ('o', 1)]8[('S01', 'S02'), ('S01', 'S03'), ('S02', 'S03')][('a', 1), ('b', 2), ('c', 0)]['P001', 'P002', 'P003']functools and operator
Section titled “functools and operator”| Tool | Does | Example |
|---|---|---|
partial(f, *args, **kw) |
a new function with some arguments fixed | round2 = partial(round, ndigits=2) |
reduce(f, it, initial) |
folds f(acc, x) over the items |
reduce(operator.mul, xs, 1) |
@cache |
unlimited memoization | pure functions with few distinct arguments |
@lru_cache(maxsize=128) |
memoization that drops the least recently used entry | many distinct arguments |
f.cache_info(), f.cache_clear() |
hits, misses, size; empty the cache | check that a cache works |
@wraps(f) |
copies the name and docstring to a wrapper | writing decorators (module 11) |
@total_ordering |
fills in <=, >, >= from == and < |
classes (module 20) |
@cached_property |
computes an attribute once per object | classes (module 18) |
operator.itemgetter("k") |
lambda x: x["k"]; several keys give a tuple |
sorted(rows, key=itemgetter("region", "revenue")) |
operator.attrgetter("k") |
lambda x: x.k |
max(stores, key=attrgetter("size_sqm")) |
operator.add, mul, neg, … |
operators as functions | reduce(operator.add, counters) |
import operatorfrom functools import cache, partial, reducefrom operator import itemgetter
round2 = partial(round, ndigits=2)print(round2(3.14159), round2.keywords)print(reduce(operator.mul, [1.05, 0.98, 1.10], 1.0))
@cachedef fib(n): # the classic memoization demo return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60), fib.cache_info().misses) # 61 real calls instead of billions
rows = [{"region": "West", "revenue": 66.49}, {"region": "East", "revenue": 79.99}]print([r["region"] for r in sorted(rows, key=itemgetter("revenue"), reverse=True)])3.14 {'ndigits': 2}1.13191548008755920 61['East', 'West']datetime and zoneinfo
Section titled “datetime and zoneinfo”| Task | Code | Result |
|---|---|---|
| a date / a datetime | date(2024, 5, 1), datetime(2024, 5, 1, 8, 25) |
|
| parse ISO text | date.fromisoformat("2024-05-01"), datetime.fromisoformat("2024-05-01T08:25:13") |
|
| parse other layouts | datetime.strptime("07/01/2023", "%d/%m/%Y") |
7 January 2023 |
| format | d.isoformat(), d.strftime("%d %b %Y"), f"{d:%Y-%m}" |
'2024-05' |
| parts | .year, .month, .day, .hour, .weekday() (Mon = 0), .isoweekday() (Mon = 1) |
|
| ISO week | d.isocalendar().week, date.fromisocalendar(2024, 48, 1) |
Monday of week 48 |
| a date from a datetime | dt.date(), dt.time() |
|
| duration | timedelta(days=1, hours=2, minutes=30), .total_seconds(), .days |
|
| count intervals | (end - start) // timedelta(minutes=10) |
an int |
| compare and sort | <, ==, max(), sorted() |
chronological |
| aware UTC | datetime(..., tzinfo=UTC), naive.replace(tzinfo=UTC) |
from datetime import UTC (3.11+) |
| convert zones | dt.astimezone(ZoneInfo("Europe/Berlin")) |
same moment, other clock |
| zone name and offset | dt.tzname(), dt.utcoffset(), f"{dt:%Z %z}" |
CDT -0500 |
| the current time | datetime.now(UTC) |
never the naive datetime.now() |
| Code | Meaning | Code | Meaning |
|---|---|---|---|
%Y |
4-digit year | %H |
hour 00–23 |
%y |
2-digit year | %I, %p |
hour 01–12, AM/PM |
%m |
month 01–12 | %M |
minute |
%d |
day 01–31 | %S |
second |
%B, %b |
January, Jan |
%f |
microseconds |
%A, %a |
Monday, Mon |
%z, %Z |
-0500, CDT |
%j |
day of the year | %% |
a literal % |
from datetime import UTC, date, datetime, timedeltafrom zoneinfo import ZoneInfo
day = date.fromisoformat("2024-11-29") # Black Friday 2024print(day.strftime("%A %d %B"), day.isocalendar().week, f"{day:%Y-%m}")start = datetime(2024, 5, 1)print(start + 1000 * timedelta(minutes=10), (datetime(2024, 5, 2) - start).days)
logged = datetime.fromisoformat("2024-05-01 13:25:00").replace(tzinfo=UTC)for zone in ["America/Chicago", "Europe/Berlin", "Asia/Kolkata"]: print(f"{zone:<16}{logged.astimezone(ZoneInfo(zone)):%H:%M %Z (%z)}")
chicago = ZoneInfo("America/Chicago")a = datetime(2024, 11, 2, 12, tzinfo=chicago)b = datetime(2024, 11, 3, 12, tzinfo=chicago) # clocks went back at 02:00print(b - a, b.astimezone(UTC) - a.astimezone(UTC)) # wall clock vs real timeFriday 29 November 48 2024-112024-05-07 22:40:00 1America/Chicago 08:25 CDT (-0500)Europe/Berlin 15:25 CEST (+0200)Asia/Kolkata 18:55 IST (+0530)1 day, 0:00:00 1 day, 1:00:00re: regular expressions
Section titled “re: regular expressions”| Syntax | Meaning | Syntax | Meaning |
|---|---|---|---|
. |
any character but \n |
^, $ |
start, end (of each line with re.M) |
\d, \D |
digit, non-digit | \b, \B |
word boundary, not a boundary |
\w, \W |
word character, other | *, +, ? |
0+, 1+, 0 or 1 (greedy) |
\s, \S |
whitespace, other | *?, +?, ?? |
the same, lazy |
[abc], [^abc] |
one of, none of | {n}, {m,n}, {m,} |
repeat counts |
[a-z0-9] |
ranges | a|b |
a or b |
\., \[, \\ |
literal ., [, \ |
(...) |
capturing group |
(?P<name>...) |
named group | (?:...) |
group without capture |
(?=...), (?!...) |
followed by, not followed by | \1, \g<name> |
backreference in sub |
| Function | Returns | Flag | Effect |
|---|---|---|---|
search(p, s) |
first match anywhere or None |
re.IGNORECASE (re.I) |
ignore case |
match(p, s) |
match at the start or None |
re.MULTILINE (re.M) |
^ and $ per line |
fullmatch(p, s) |
match of the whole string or None |
re.DOTALL (re.S) |
. also matches \n |
findall(p, s) |
strings, or tuples of groups | re.VERBOSE (re.X) |
spaces and # comments in the pattern |
finditer(p, s) |
match objects | re.ASCII (re.A) |
\w, \d only ASCII |
sub(p, repl, s, count=0) |
new string; repl can be a function |
combine | re.I | re.M |
split(p, s, maxsplit=0) |
list of pieces | ||
compile(p, flags) |
a pattern with the same methods |
| Match object | Gives |
|---|---|
m.group() / m[0] |
the whole match |
m.group(1) / m[1], m["name"] |
one group |
m.groups(), m.groupdict() |
all groups as a tuple, named groups as a dict |
m.start(), m.end(), m.span() |
positions in the string |
| Data pattern | Regex |
|---|---|
| ISO date | \d{4}-\d{2}-\d{2} |
an id such as O000123 |
\bO\d{6}\b |
| a decimal number, optional sign | [-+]?\d+(?:\.\d+)? |
a price such as $1,299.00 |
\$(\d{1,3}(?:,\d{3})*\.\d{2}) |
| a simple email | [\w.+-]+@[\w-]+\.[\w.]+ |
| an IPv4 address | \b\d{1,3}(?:\.\d{1,3}){3}\b |
| a log level word | \b(?:DEBUG|INFO|WARNING|ERROR)\b |
import re
line = "2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms"API = r"(?P<method>GET|POST) (?P<path>\S+) (?P<status>\d{3}) (?P<ms>\d+)ms"m = re.search(API, line)print(m["method"], m.group("path"), int(m["status"]), m.span("ms"))print(re.findall(r"\$(\d{1,3}(?:,\d{3})*\.\d{2})", "was $1,299.00, now $999.00"))print(re.sub(r"\$|,", "", "$1,299.00"), re.split(r"\s*;\s*", "a ; b;c"))print(re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\2-\1", "07/01/2023")) # DD/MM/YYYYprint(re.findall(r"^\w+", "INFO a\nWARN b", flags=re.MULTILINE))print(bool(re.fullmatch(r"P\d{3}", "P0011")), bool(re.search(r"error", "ERROR", re.I)))POST /api/v1/predict 201 (71, 73)['1,299.00', '999.00']1299.00 ['a', 'b', 'c']2023-01-07['INFO', 'WARN']False Truemath, statistics and random
Section titled “math, statistics and random”math |
Does | statistics |
Does |
|---|---|---|---|
sqrt, isqrt, exp, log(x, base), log10, log2 |
powers and logs | mean, fmean |
arithmetic mean (fmean: fast, floats) |
floor, ceil, trunc |
rounding to integers | median, median_low, median_high |
middle value |
isclose(a, b, rel_tol, abs_tol) |
float comparison | mode, multimode |
most common value(s) |
fsum(xs) |
exact float sum | stdev, variance |
sample (n − 1) |
prod(xs) |
product | pstdev, pvariance |
population (n) |
comb(n, k), perm(n, k), factorial(n) |
counting | quantiles(xs, n=4) |
n − 1 cut points |
dist(p, q), hypot(x, y) |
Euclidean distance | correlation(x, y) |
Pearson correlation |
inf, nan, isnan, isinf, pi, e |
special values | linear_regression(x, y) |
slope and intercept |
gcd, lcm |
integer helpers | NormalDist(mu, sigma) |
cdf, inv_cdf, pdf, zscore |
random.Random(42) method |
Does |
|---|---|
random(), uniform(a, b) |
float in [0, 1), in [a, b] |
randint(a, b), randrange(start, stop, step) |
integer, both ends included / stop excluded |
choice(seq) |
one item |
choices(seq, weights=None, k=1) |
k items with replacement (bootstrap) |
sample(seq, k) |
k distinct items without replacement |
shuffle(list) |
reorders the list in place, returns None |
gauss(mu, sigma), expovariate(lambd) |
normal and exponential draws |
import mathimport randomimport statistics
sizes = [2850, 1950, 1420, 3100, 2300, 1680, 3400, 2050, 1760, 2480, 1890, 1350]lines = [2220, 1563, 1183, 2199, 1745, 1200, 2541, 1541, 1314, 2190, 1664, 868]print(round(statistics.correlation(sizes, lines), 3)) # store size vs sales linesfit = statistics.linear_regression(sizes, lines)print(round(fit.slope, 3), round(fit.intercept, 1))print([round(q) for q in statistics.quantiles(lines, n=4)], statistics.median(lines))print(round(statistics.NormalDist(0, 1).inv_cdf(0.975), 3), math.comb(12, 2))
rng = random.Random(42)print(rng.sample(["S01", "S02", "S03", "S04"], 2), rng.choices([0, 1], [9, 1], k=8))0.9620.749 48.9[1228, 1614, 2197] 1613.51.96 66['S01', 'S04'] [0, 0, 0, 0, 0, 0, 0, 0]os, sys, shutil and subprocess
Section titled “os, sys, shutil and subprocess”| Call | Does |
|---|---|
os.environ["K"], os.environ.get("K", "default") |
read a setting (always a str) |
os.environ["K"] = "v" |
set it for this process and its children |
os.getcwd(), os.chdir(p) |
the working folder (prefer Path.cwd()) |
os.cpu_count() |
number of CPUs (for worker pools) |
os.sep, os.linesep |
/ or \; \n or \r\n |
sys.argv |
command-line words |
sys.executable |
path of the running Python |
sys.version_info >= (3, 12) |
version check |
sys.platform |
"darwin", "linux", "win32" |
sys.exit(0), sys.exit("msg") |
exit code 0; message to stderr and exit code 1 |
print(..., file=sys.stderr) |
write to the error stream |
shutil.copy(src, dst) / copy2 |
copy a file / with its metadata |
shutil.copytree(src, dst, dirs_exist_ok=True) |
copy a folder |
shutil.move(src, dst) |
move or rename |
shutil.rmtree(path, ignore_errors=True) |
delete a folder tree, no undo |
shutil.make_archive(base, "zip", root_dir), unpack_archive(file, dst) |
zip and unzip |
shutil.which("git") |
a program’s path, or None |
shutil.disk_usage(".") |
total, used, free bytes |
subprocess.run(...) argument |
Effect |
|---|---|
[program, arg1, arg2] |
the command as a list; no shell |
capture_output=True |
keep stdout and stderr in the result |
text=True |
decode output to str |
check=True |
raise CalledProcessError on a non-zero exit code |
timeout=60 |
raise TimeoutExpired after 60 seconds |
cwd="folder" |
run in another folder |
env={**os.environ, "K": "v"} |
the child’s environment |
input="text" |
send text to the child’s stdin |
| Result | Holds |
|---|---|
result.returncode |
the exit code |
result.stdout, result.stderr |
the captured output |
error.returncode, error.stderr |
the same, on a CalledProcessError |
import osimport subprocessimport sys
os.environ["RUN_LABEL"] = "nightly"result = subprocess.run( [sys.executable, "-c", "import os; print(os.environ['RUN_LABEL'].upper())"], capture_output=True, text=True, check=True,)print(result.returncode, result.stdout.strip())result = subprocess.run( [sys.executable, "-c", "import sys; print(sum(map(int, sys.stdin)))"], input="3\n4\n5\n", capture_output=True, text=True, check=True,)print(result.stdout.strip())try: subprocess.run([sys.executable, "-c", "raise SystemExit(4)"], check=True)except subprocess.CalledProcessError as error: print("failed with exit code", error.returncode)0 NIGHTLY12failed with exit code 4Gotchas
Section titled “Gotchas”| Gotcha | What happens | Do this |
|---|---|---|
groupby on unsorted data |
one group per run, keys repeat | sort by the same key first |
| An iterator used twice | the second pass is empty, no error | build it again or store a list |
Reading dd[missing] on a defaultdict |
creates the key | dd.get(k) or k in dd |
Counter - Counter |
negative and zero counts vanish | c.subtract(other) keeps them |
deque without maxlen |
grows forever | deque(maxlen=n) |
namedtuple field change |
AttributeError: can't set attribute |
r._replace(field=value) |
batched(..., strict=True) |
only on Python 3.13+ | check the last batch yourself on 3.12 |
@cache on a method or with list arguments |
memory never freed; TypeError: unhashable type |
cache module-level pure functions; pass tuples |
| A cached mutable result | callers share and change one object | return tuples or frozensets |
reduce without an initial value on an empty list |
TypeError: reduce() of empty iterable with no initial value |
pass the initial value |
| Naive and aware datetimes mixed | TypeError on - and < |
make everything aware in UTC |
| Same-zone subtraction across DST | wall-clock difference, off by 1 hour | subtract in UTC |
%m/%d versus %d/%m |
7 January read as July 1, no error | know your source; test a day above 12 |
datetime.now() |
naive local time, differs per machine | datetime.now(UTC) |
ZoneInfo on Windows without tzdata |
ZoneInfoNotFoundError |
pip install tzdata |
A regex without r"..." |
\b is a backspace; SyntaxWarning for \d |
always use raw strings |
re.match versus re.search |
match only checks the start |
search anywhere, fullmatch for validation |
findall with groups |
returns groups, not whole matches | use (?:...) or finditer |
Greedy .* |
one match spans several fields | .*? or \S+ |
statistics.stdev with one value |
StatisticsError: stdev requires at least two data points |
check the length first |
stdev versus pstdev |
differs from pandas or NumPy | pandas .std() = stdev; NumPy np.std() = pstdev |
random.seed(42) plus global functions |
other code shifts your sequence | rng = random.Random(42) |
random.shuffle(xs) result |
returns None |
shuffle in place, then use xs |
os.environ["MISSING"] |
KeyError |
os.environ.get("MISSING", default) |
| Environment values | always strings: "0" is truthy |
convert: int(...), value == "1" |
shutil.copytree into an existing folder |
FileExistsError |
dirs_exist_ok=True |
subprocess.run("python x.py", shell=True) |
shell injection risk, wrong Python | [sys.executable, "x.py"] |
subprocess.run without check=True |
failures pass silently | check=True |
Printing sys.executable, paths or versions |
output differs per machine | print comparisons or relative paths |