Join / Split Pathlib
Python Top Commands '-'.join(list_) | [Link](',') from pathlib import Path; list(Path('.').glob('**/*.py'))
/ Idioms Cheatsheet Strip / Replace CSV
[Link]() | [Link]('a','b') import csv; [Link](f); [Link](f, fieldnames=...)
Run / REPL
Find / startswith JSON
python [Link] | python -i | python -m module
[Link]('x') | [Link]('pre') import json; [Link](obj); [Link](s)
Version / Help
Format datetime
python --version | python -m pip --help
'{name}:{age}'.format(name=n, age=a) from datetime import datetime as dt; [Link]().isoformat()
Time a command
Regex timedelta
python -m timeit "sum(range(10_000))"
import re; [Link](r"\d+", s) from datetime import timedelta; [Link]()+timedelta(days=3)
Start venv
List literal/comp timezone
python -m venv .venv && source .venv/bin/activate (Win:
.venv\Scripts\activate) [1,2,3] | [x*x for x in it if x>0] from datetime import timezone; [Link]([Link])
Install pkg Append/extend env & cwd
python -m pip install <pkg> | python -m pip freeze [Link](x); [Link]([1,2]) import os; [Link]('HOME'); [Link]()
Print & f-strings Sort listdir
print(f"x={x:.2f}") [Link](key=len, reverse=True) | sorted(a) [Link]('.'); [Link]('.')
Input Slicing ops subprocess
name = input("Name: ") a[:], a[::2], del a[:2] import subprocess as sp; [Link](['ls','-l'], check=True)
Walrus Dict literal/comp math
if (n := len(seq)) > 0: ... {'k':1} | {k: f(k) for k in it} import math; [Link](9); [Link]
Unpacking Get / setdefault statistics
a, b = (1, 2); a, *mid, b = range(5) [Link]('k', 0) | [Link]('k', []) import statistics as stats; [Link]([1,2,3])
Ternary Items / keys random
x = a if cond else b for k, v in [Link](): ... import random as r; [Link](seq); [Link](seq, k=3)
Truthiness Merge Counter / deque
if obj: ... # empty= False {**d1, **d2} | d1 | d2 (3.9+) from collections import Counter, deque
Type / isinstance Sets defaultdict
type(x) | isinstance(x, (int, str)) {1,2,3}; a & b; a | b; a - b; a ^ b from collections import defaultdict; dd=defaultdict(list)
Convert Tuples / namedtuple OrderedDict
int('3'), float('1.2'), str(10), list('abc') t = (1,2); from collections import namedtuple from collections import OrderedDict # Py3.7+ dicts keep order
Slice Open file heapq
seq[start:stop:step] | seq[::-1] with open('[Link]','r',encoding='utf-8') as f: data=[Link]() import heapq as hq; [Link](h, x); [Link](h)
Enumerate / zip Write file bisect
for i, v in enumerate(seq): ... | for a,b in zip(A,B): ... Path('[Link]').write_text('hi', encoding='utf-8') import bisect; i = bisect.bisect_left(a, x)
map/filter wraps
list(map(f, it)); list(filter(pred, it)) from functools import wraps # preserve metadata
any/all/sum async/await
any(pred(x) for x in it); all(...); sum(it) async def f(): await coro()
itertools gather
from itertools import chain, groupby, combinations import asyncio; await [Link](*cors)
functools to run
from functools import lru_cache, partial, reduce [Link](main()) # top-level entry
try/except pdb
try: ... except ValueError as e: ... else: ... finally: ... python -m pdb [Link] | import pdb; pdb.set_trace()
raise logging
raise ValueError('msg') import logging; [Link](level=[Link])
assert unittest/pytest
assert cond, 'message' python -m unittest | pytest -k test_name -q
def / *args/**kwargs warnings
def f(a,*args,**kw): ... import warnings; [Link]('msg')
lambda timeit
key=lambda x: x[1] import timeit; [Link]('x=2+2')
annotations profilers
def f(x: int) -> str: ... python -m cProfile [Link] | snakeviz stats
dataclass pickle
from dataclasses import dataclass; @dataclass class P: x:int; import pickle; [Link](obj,f); [Link](f)
y:int copy
property
import copy; [Link](x); [Link](x)
class C: @property def x(self): return 42 typing
yield / gen
from typing import Optional, Iterable, TypedDict, Literal,
def gen(): yield from range(3) Union
with / contextlib List/dict comps
from contextlib import contextmanager [f(x) for x in xs] | {k:v for k,v in pairs}
ExitStack Generator expr
from contextlib import ExitStack (x*x for x in xs)
Decorator EAFP
def deco(f): ...; @deco def g(): ... Easier to Ask Forgiveness than Permission: try/except style