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

Open full cheat sheet
UseSyntaxExamples
Read a monotonic performance clockstarted = time.perf_counter()View examples
Read integer nanosecondsstarted_ns = time.perf_counter_ns()View examples
Record interpreter identityidentity = (sys.implementation.name, platform.python_version())View examples
Time a callableseconds = timeit.timeit(callable_under_test, number=1000)View examples
Collect repeated timingssamples = timeit.repeat(stmt, setup=setup, repeat=7, number=1000)View examples
Run the timeit CLIpython -m timeit -s 'data = list(range(100))' 'sum(data)'View examples
Profile a callableprofile.runcall(main)View examples
Profile a module to a filepython -m cProfile -o profile.pstats -m package.moduleView examples
Sort by cumulative timestats.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)View examples
Start allocation tracingtracemalloc.start(10)View examples
Capture allocationssnapshot = tracemalloc.take_snapshot()View examples
Compare snapshotsdiff = after.compare_to(before, 'lineno')View examples
Install a trace hookprevious = sys.gettrace(); sys.settrace(trace_function)View examples
Restore a trace hooksys.settrace(previous)View examples
Trace threading workersthreading.settrace(trace_function)View examples
Enable fault tracebacksfaulthandler.enable()View examples
Inspect current thread framesframes = sys._current_frames()View examples
Summarize the medianmiddle = statistics.median(samples)View examples
Compute quartile cut pointsquartiles = statistics.quantiles(samples, n=4, method='inclusive')View examples

Concurrency, Networking, and Performance · 18 commands

Python Sockets and Selectors Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Resolve stream candidatesaddresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)View examples
Open a TCP connectionsock = socket.create_connection((host, port), timeout=5.0)View examples
Close a socket reliablywith socket.socket() as sock: use(sock)View examples
Send the full buffersock.sendall(payload)View examples
Detect stream EOFchunk = sock.recv(65536)View examples
Encode a network-order lengthheader = struct.pack('!I', len(payload))View examples
Bind an ephemeral loopback portlistener.bind(('127.0.0.1', 0))View examples
Start listeninglistener.listen(128)View examples
Accept one connectionconnection, address = listener.accept()View examples
Set an operation timeoutsock.settimeout(2.0)View examples
Enable non-blocking modesock.setblocking(False)View examples
Register read interestselector.register(sock, selectors.EVENT_READ, data=state)View examples
Wait for readinessevents = selector.select(timeout=1.0)View examples
Change event interestselector.modify(sock, selectors.EVENT_READ | selectors.EVENT_WRITE, state)View examples
Send a UDP datagramsent = sock.sendto(payload, destination)View examples
Receive a UDP datagrampayload, peer = sock.recvfrom(65507)View examples
Half-close the write sidesock.shutdown(socket.SHUT_WR)View examples
Create safe client TLS defaultscontext = ssl.create_default_context()View examples

Concurrency, Networking, and Performance · 16 commands

Python sqlite3 Databases Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Open an in-memory databasecon = sqlite3.connect(':memory:')View examples
Open a database filecon = sqlite3.connect('app.db', timeout=5.0)View examples
Create a table safelycon.execute('CREATE TABLE IF NOT EXISTS task(id INTEGER PRIMARY KEY, title TEXT NOT NULL)')View examples
Bind positional valuescon.execute('SELECT * FROM task WHERE id = ?', (task_id,))View examples
Bind named valuescon.execute('UPDATE task SET done = :done WHERE id = :id', {'done': 1, 'id': task_id})View examples
Insert a batchcon.executemany('INSERT INTO task(title) VALUES(?)', [(title,) for title in titles])View examples
Commit or roll back a unitwith con: con.execute('UPDATE account SET balance = balance - ? WHERE id = ?', (amount, account_id))View examples
Select PEP 249 controlcon = sqlite3.connect('app.db', autocommit=False)View examples
Inspect transaction stateif con.in_transaction: con.rollback()View examples
Enforce foreign keyscon.execute('PRAGMA foreign_keys = ON')View examples
Handle constraint failuresexcept sqlite3.IntegrityError as error: con.rollback()View examples
Read columns by namecon.row_factory = sqlite3.RowView examples
Fetch one resultrow = con.execute('SELECT title FROM task WHERE id = ?', (task_id,)).fetchone()View examples
Create a nested recovery pointcon.execute('SAVEPOINT before_optional_work')View examples
Undo to a savepointcon.execute('ROLLBACK TO SAVEPOINT before_optional_work')View examples
Copy a live databasesource.backup(destination, pages=100)View examples

Concurrency, Networking, and Performance · 19 commands

Python Threading and Synchronization Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Start a threadworker.start()View examples
Wait with a deadlineworker.join(timeout=2.0)View examples
Name a workerworker = threading.Thread(name='indexer', target=build_index)View examples
Guard a critical sectionwith lock: update_shared_state()View examples
Attempt bounded acquisitionacquired = lock.acquire(timeout=0.5)View examples
Create a reentrant locklock = threading.RLock()View examples
Wait for a predicateready = condition.wait_for(predicate, timeout=1.0)View examples
Notify one waitercondition.notify()View examples
Request cooperative stopstop_event.set()View examples
Limit concurrent entrieslimit = threading.Semaphore(4)View examples
Detect excess releaselimit = threading.BoundedSemaphore(value=4)View examples
Create a phase barrierbarrier = threading.Barrier(parties=3, timeout=5.0)View examples
Arrive at a barrierindex = barrier.wait()View examples
Abort a barrierbarrier.abort()View examples
Create backpressurejobs = queue.Queue(maxsize=100)View examples
Acknowledge a queued taskjobs.task_done()View examples
Wait for task acknowledgementsjobs.join()View examples
Check completion after joinif worker.is_alive(): handle_timeout()View examples
Install an exception observerthreading.excepthook = report_thread_failureView examples

Concurrency, Networking, and Performance · 15 commands

Python urllib HTTP Clients Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Open a URLwith urlopen(request, timeout=10) as response: body = response.read(1_000_001)View examples
Build a requestrequest = Request(url, headers={'Accept': 'application/json'}, method='GET')View examples
Inspect a responsestatus, final_url = response.status, response.geturl()View examples
Decode a response bodytext = body.decode(response.headers.get_content_charset() or 'utf-8')View examples
Encode a query stringquery = urlencode({'q': 'red fox', 'page': 2})View examples
Encode repeated parametersquery = urlencode({'tag': ['python', 'web']}, doseq=True)View examples
Build a form POSTrequest = Request(url, data=urlencode(fields).encode('ascii'), method='POST')View examples
Split a URLparts = urlsplit(candidate)View examples
Quote a path segmentsegment = quote(user_value, safe='')View examples
Resolve a relative URLnext_url = urljoin(base_url, relative_url)View examples
Catch HTTP status errorsexcept HTTPError as error: status = error.codeView examples
Catch transport errorsexcept URLError as error: reason = error.reasonView examples
Create verified TLS settingscontext = ssl.create_default_context()View examples
Disable inherited proxiesopener = build_opener(ProxyHandler({}))View examples
Keep a header off redirectsrequest.add_unredirected_header('Authorization', token)View examples
CMDMEMO TERMINALREAD ONLY