176 commands · 10 cheat sheets · Python
Concurrency, Networking, and Performance master quick reference
Browse 176 commands from 10 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.
Concurrency, Networking, and Performance · 12 commands
Python asyncio and await Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Define a coroutine | async def fetch(): return await client.get('/') | View examples |
| Run an entry coroutine | asyncio.run(main()) | View examples |
| Await completion | result = await operation() | View examples |
| Schedule a task | task = asyncio.create_task(operation()) | View examples |
| Group child tasks | async with asyncio.TaskGroup() as group: group.create_task(operation()) | View examples |
| Collect ordered results | results = await asyncio.gather(*coroutines) | View examples |
| Bound a block by time | async with asyncio.timeout(5): result = await operation() | View examples |
| Request cancellation | task.cancel() | View examples |
| Yield to the loop | await asyncio.sleep(0) | View examples |
| Create a bounded queue | queue = asyncio.Queue(maxsize=100) | View examples |
| Bound concurrent access | async with asyncio.Semaphore(10): await operation() | View examples |
| Run blocking I/O in a thread | result = await asyncio.to_thread(blocking_function, argument) | View examples |
Concurrency, Networking, and Performance · 16 commands
Python concurrent.futures and Parallel Work Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a thread pool | with ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(fetch, urls)) | View examples |
| Create a process pool | with ProcessPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values)) | View examples |
| Create an interpreter pool | with InterpreterPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_task, values)) | View examples |
| Submit one call | future = executor.submit(function, argument) | View examples |
| Retrieve a result | value = future.result(timeout=5) | View examples |
| Add a completion callback | future.add_done_callback(record_completion) | View examples |
| Map in input order | results = executor.map(function, items) | View examples |
| Bound submitted map work | results = executor.map(function, items, buffersize=16) | View examples |
| Batch process-pool items | results = executor.map(function, items, chunksize=64) | View examples |
| Consume completed futures | results = [future.result() for future in as_completed(futures)] | View examples |
| Wait for a condition | done, pending = wait(futures, timeout=5, return_when=FIRST_EXCEPTION) | View examples |
| Limit a result wait | future.result(timeout=2) | View examples |
| Cancel pending work | cancelled = future.cancel() | View examples |
| Shut down an executor | executor.shutdown(wait=True, cancel_futures=True) | View examples |
| Guard process entry | if __name__ == '__main__': main() | View examples |
| Choose a process context | ProcessPoolExecutor(mp_context=multiprocessing.get_context('spawn')) | View examples |
Concurrency, Networking, and Performance · 20 commands
Python Hashing, HMAC, and Secrets Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Hash bytes with SHA-256 | digest = hashlib.sha256(data).digest() | View examples |
| Render a hexadecimal digest | text = hashlib.sha256(data).hexdigest() | View examples |
| Hash data incrementally | hasher.update(chunk) | View examples |
| Hash an open binary file | with path.open('rb') as file: digest = hashlib.file_digest(file, 'sha256') | View examples |
| Branch a partial hash | branch = hasher.copy() | View examples |
| Construct an algorithm by name | hasher = hashlib.new('sha256', data) | View examples |
| Inspect portable algorithms | portable = hashlib.algorithms_guaranteed | View examples |
| Build an HMAC incrementally | mac = hmac.new(key, message, digestmod=hashlib.sha256) | View examples |
| Calculate an HMAC in one call | tag = hmac.digest(key, message, 'sha256') | View examples |
| Compare authenticators safely | valid = hmac.compare_digest(received_tag, expected_tag) | View examples |
| Generate random secret bytes | key = secrets.token_bytes(32) | View examples |
| Generate a hexadecimal token | token = secrets.token_hex(32) | View examples |
| Generate a URL-safe token | token = secrets.token_urlsafe(32) | View examples |
| Choose securely from a sequence | character = secrets.choice(alphabet) | View examples |
| Generate a bounded integer | index = secrets.randbelow(exclusive_upper_bound) | View examples |
| Derive a PBKDF2 verifier | derived = hashlib.pbkdf2_hmac('sha256', password, salt, iterations, dklen=32) | View examples |
| Derive a scrypt verifier | derived = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1, dklen=32) | View examples |
| Create a unique password salt | salt = secrets.token_bytes(16) | View examples |
| Authenticate with keyed BLAKE2 | tag = hashlib.blake2b(message, key=key, digest_size=32).digest() | View examples |
| Separate BLAKE2 domains | digest = hashlib.blake2b(data, person=b'cache-v1', digest_size=16).digest() | View examples |
Concurrency, Networking, and Performance · 15 commands
Python Memory, Garbage Collection, and Weak References Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Measure shallow size | shallow_bytes = sys.getsizeof(value) | View examples |
| Inspect CPython references | count_with_temporary = sys.getrefcount(value) | View examples |
| Run cyclic collection | unreachable = gc.collect() | View examples |
| Check collector state | collector_enabled = gc.isenabled() | View examples |
| Read GC thresholds | thresholds = gc.get_threshold() | View examples |
| Freeze tracked objects | gc.freeze() | View examples |
| Create a weak reference | reference = weakref.ref(instance) | View examples |
| Cache values weakly | cache = weakref.WeakValueDictionary() | View examples |
| Associate metadata weakly | metadata = weakref.WeakKeyDictionary() | View examples |
| Track instances weakly | instances = weakref.WeakSet() | View examples |
| Register a finalizer | cleanup = weakref.finalize(owner, close_resource, resource_id) | View examples |
| Start allocation tracing | tracemalloc.start(10) | View examples |
| Capture a snapshot | snapshot = tracemalloc.take_snapshot() | View examples |
| Compare snapshots | changes = after.compare_to(before, 'lineno') | View examples |
| Read traced current and peak | current, peak = tracemalloc.get_traced_memory() | View examples |
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 |



