Join / Split Pathlib
Python Top Commands '-'.join(list_) | s.split(',') from pathlib import Path; list(Path('.').glob('**/*.py'))
/ Idioms Cheatsheet Strip / Replace CSV
s.strip() | s.replace('a','b') import csv; csv.reader(f); csv.DictWriter(f, fieldnames=...)
Run / REPL
Find / startswith JSON
python script.py | python -i | python -m module
s.find('x') | s.startswith('pre') import json; json.dumps(obj); json.loads(s)
Version / Help
Format datetime
python --version | python -m pip --help
'{name}:{age}'.format(name=n, age=a) from datetime import datetime as dt; dt.now().isoformat()
Time a command
Regex timedelta
python -m timeit "sum(range(10_000))"
import re; re.findall(r"\d+", s) from datetime import timedelta; dt.now()+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; dt.now(timezone.utc)
Install pkg Append/extend env & cwd
python -m pip install <pkg> | python -m pip freeze a.append(x); a.extend([1,2]) import os; os.getenv('HOME'); os.getcwd()
Print & f-strings Sort listdir
print(f"x={x:.2f}") a.sort(key=len, reverse=True) | sorted(a) os.listdir('.'); os.walk('.')
Input Slicing ops subprocess
name = input("Name: ") a[:], a[::2], del a[:2] import subprocess as sp; sp.run(['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; math.sqrt(9); math.pi
Unpacking Get / setdefault statistics
a, b = (1, 2); a, *mid, b = range(5) d.get('k', 0) | d.setdefault('k', []) import statistics as stats; stats.mean([1,2,3])
Ternary Items / keys random
x = a if cond else b for k, v in d.items(): ... import random as r; r.choice(seq); r.sample(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('a.txt','r',encoding='utf-8') as f: data=f.read() import heapq as hq; hq.heappush(h, x); hq.heappop(h)
Enumerate / zip Write file bisect
for i, v in enumerate(seq): ... | for a,b in zip(A,B): ... Path('x.txt').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 asyncio.gather(*cors)
functools to run
from functools import lru_cache, partial, reduce asyncio.run(main()) # top-level entry
try/except pdb
try: ... except ValueError as e: ... else: ... finally: ... python -m pdb script.py | import pdb; pdb.set_trace()
raise logging
raise ValueError('msg') import logging; logging.basicConfig(level=logging.INFO)
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; warnings.warn('msg')
lambda timeit
key=lambda x: x[1] import timeit; timeit.timeit('x=2+2')
annotations profilers
def f(x: int) -> str: ... python -m cProfile script.py | snakeviz stats
dataclass pickle
from dataclasses import dataclass; @dataclass class P: x:int; import pickle; pickle.dump(obj,f); pickle.load(f)
y:int copy
property
import copy; copy.copy(x); copy.deepcopy(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