888 commands · 53 cheat sheets · 7 subcategories
Python master quick reference — Page 5
Browse 87 commands from 5 focused cheat sheets on page 5 of 5. Each example opens its matching detailed section.
Concurrency, Networking, and Performance · 19 commands
Python Profiling, Benchmarking, and Tracing Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Read a monotonic performance clock | started = time.perf_counter() | View examples |
| Read integer nanoseconds | started_ns = time.perf_counter_ns() | View examples |
| Record interpreter identity | identity = (sys.implementation.name, platform.python_version()) | View examples |
| Time a callable | seconds = timeit.timeit(callable_under_test, number=1000) | View examples |
| Collect repeated timings | samples = timeit.repeat(stmt, setup=setup, repeat=7, number=1000) | View examples |
| Run the timeit CLI | python -m timeit -s 'data = list(range(100))' 'sum(data)' | View examples |
| Profile a callable | profile.runcall(main) | View examples |
| Profile a module to a file | python -m cProfile -o profile.pstats -m package.module | View examples |
| Sort by cumulative time | stats.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20) | View examples |
| Start allocation tracing | tracemalloc.start(10) | View examples |
| Capture allocations | snapshot = tracemalloc.take_snapshot() | View examples |
| Compare snapshots | diff = after.compare_to(before, 'lineno') | View examples |
| Install a trace hook | previous = sys.gettrace(); sys.settrace(trace_function) | View examples |
| Restore a trace hook | sys.settrace(previous) | View examples |
| Trace threading workers | threading.settrace(trace_function) | View examples |
| Enable fault tracebacks | faulthandler.enable() | View examples |
| Inspect current thread frames | frames = sys._current_frames() | View examples |
| Summarize the median | middle = statistics.median(samples) | View examples |
| Compute quartile cut points | quartiles = statistics.quantiles(samples, n=4, method='inclusive') | View examples |
Concurrency, Networking, and Performance · 18 commands
Python Sockets and Selectors Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Resolve stream candidates | addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) | View examples |
| Open a TCP connection | sock = socket.create_connection((host, port), timeout=5.0) | View examples |
| Close a socket reliably | with socket.socket() as sock: use(sock) | View examples |
| Send the full buffer | sock.sendall(payload) | View examples |
| Detect stream EOF | chunk = sock.recv(65536) | View examples |
| Encode a network-order length | header = struct.pack('!I', len(payload)) | View examples |
| Bind an ephemeral loopback port | listener.bind(('127.0.0.1', 0)) | View examples |
| Start listening | listener.listen(128) | View examples |
| Accept one connection | connection, address = listener.accept() | View examples |
| Set an operation timeout | sock.settimeout(2.0) | View examples |
| Enable non-blocking mode | sock.setblocking(False) | View examples |
| Register read interest | selector.register(sock, selectors.EVENT_READ, data=state) | View examples |
| Wait for readiness | events = selector.select(timeout=1.0) | View examples |
| Change event interest | selector.modify(sock, selectors.EVENT_READ | selectors.EVENT_WRITE, state) | View examples |
| Send a UDP datagram | sent = sock.sendto(payload, destination) | View examples |
| Receive a UDP datagram | payload, peer = sock.recvfrom(65507) | View examples |
| Half-close the write side | sock.shutdown(socket.SHUT_WR) | View examples |
| Create safe client TLS defaults | context = ssl.create_default_context() | View examples |
Concurrency, Networking, and Performance · 16 commands
Python sqlite3 Databases Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Open an in-memory database | con = sqlite3.connect(':memory:') | View examples |
| Open a database file | con = sqlite3.connect('app.db', timeout=5.0) | View examples |
| Create a table safely | con.execute('CREATE TABLE IF NOT EXISTS task(id INTEGER PRIMARY KEY, title TEXT NOT NULL)') | View examples |
| Bind positional values | con.execute('SELECT * FROM task WHERE id = ?', (task_id,)) | View examples |
| Bind named values | con.execute('UPDATE task SET done = :done WHERE id = :id', {'done': 1, 'id': task_id}) | View examples |
| Insert a batch | con.executemany('INSERT INTO task(title) VALUES(?)', [(title,) for title in titles]) | View examples |
| Commit or roll back a unit | with con: con.execute('UPDATE account SET balance = balance - ? WHERE id = ?', (amount, account_id)) | View examples |
| Select PEP 249 control | con = sqlite3.connect('app.db', autocommit=False) | View examples |
| Inspect transaction state | if con.in_transaction: con.rollback() | View examples |
| Enforce foreign keys | con.execute('PRAGMA foreign_keys = ON') | View examples |
| Handle constraint failures | except sqlite3.IntegrityError as error: con.rollback() | View examples |
| Read columns by name | con.row_factory = sqlite3.Row | View examples |
| Fetch one result | row = con.execute('SELECT title FROM task WHERE id = ?', (task_id,)).fetchone() | View examples |
| Create a nested recovery point | con.execute('SAVEPOINT before_optional_work') | View examples |
| Undo to a savepoint | con.execute('ROLLBACK TO SAVEPOINT before_optional_work') | View examples |
| Copy a live database | source.backup(destination, pages=100) | View examples |
Concurrency, Networking, and Performance · 19 commands
Python Threading and Synchronization Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Start a thread | worker.start() | View examples |
| Wait with a deadline | worker.join(timeout=2.0) | View examples |
| Name a worker | worker = threading.Thread(name='indexer', target=build_index) | View examples |
| Guard a critical section | with lock: update_shared_state() | View examples |
| Attempt bounded acquisition | acquired = lock.acquire(timeout=0.5) | View examples |
| Create a reentrant lock | lock = threading.RLock() | View examples |
| Wait for a predicate | ready = condition.wait_for(predicate, timeout=1.0) | View examples |
| Notify one waiter | condition.notify() | View examples |
| Request cooperative stop | stop_event.set() | View examples |
| Limit concurrent entries | limit = threading.Semaphore(4) | View examples |
| Detect excess release | limit = threading.BoundedSemaphore(value=4) | View examples |
| Create a phase barrier | barrier = threading.Barrier(parties=3, timeout=5.0) | View examples |
| Arrive at a barrier | index = barrier.wait() | View examples |
| Abort a barrier | barrier.abort() | View examples |
| Create backpressure | jobs = queue.Queue(maxsize=100) | View examples |
| Acknowledge a queued task | jobs.task_done() | View examples |
| Wait for task acknowledgements | jobs.join() | View examples |
| Check completion after join | if worker.is_alive(): handle_timeout() | View examples |
| Install an exception observer | threading.excepthook = report_thread_failure | View examples |
Concurrency, Networking, and Performance · 15 commands
Python urllib HTTP Clients Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Open a URL | with urlopen(request, timeout=10) as response: body = response.read(1_000_001) | View examples |
| Build a request | request = Request(url, headers={'Accept': 'application/json'}, method='GET') | View examples |
| Inspect a response | status, final_url = response.status, response.geturl() | View examples |
| Decode a response body | text = body.decode(response.headers.get_content_charset() or 'utf-8') | View examples |
| Encode a query string | query = urlencode({'q': 'red fox', 'page': 2}) | View examples |
| Encode repeated parameters | query = urlencode({'tag': ['python', 'web']}, doseq=True) | View examples |
| Build a form POST | request = Request(url, data=urlencode(fields).encode('ascii'), method='POST') | View examples |
| Split a URL | parts = urlsplit(candidate) | View examples |
| Quote a path segment | segment = quote(user_value, safe='') | View examples |
| Resolve a relative URL | next_url = urljoin(base_url, relative_url) | View examples |
| Catch HTTP status errors | except HTTPError as error: status = error.code | View examples |
| Catch transport errors | except URLError as error: reason = error.reason | View examples |
| Create verified TLS settings | context = ssl.create_default_context() | View examples |
| Disable inherited proxies | opener = build_opener(ProxyHandler({})) | View examples |
| Keep a header off redirects | request.add_unredirected_header('Authorization', token) | View examples |



