tips
107 tips Python
One command, setting or habit at a time about Python: what it does, the line to copy and a caveat or two.
Standard library 46
-
Wrap awaits in asyncio.timeout and get a TimeoutError when the time is up.
import asyncio -
StrEnum members are real strings, and auto() gives each one its lowercase name.
from enum import StrEnum, auto -
Use except* to catch some exceptions from a group and leave the others for later.
except* ValueError as eg: -
A cached_property runs its method on first access and then keeps the result on the object.
from functools import cached_property -
accumulate yields the running sum, or a running max or product if you pass a function.
from itertools import accumulate -
replace() makes a new dataclass instance with the fields you name changed.
from dataclasses import dataclass, replace -
match and case unpack sequences by shape, with guards and alternatives, from Python 3.10.
match cmd.split(): -
Summarise response times or sizes with median and percentiles using only the standard library.
import statistics -
Get the biggest or smallest n items from a large list or a generator.
import heapq -
Write dates, decimals and paths to a file without a custom encoder class.
import json -
Read or write a whole small file in one line with pathlib.
from pathlib import Path -
Compute a SHA256 checksum of a file in one call, even for big files.
import hashlib -
Number items from 1 in a loop without adding one everywhere.
for n, line in enumerate(f, start=1): -
Avoid duplicate groups from itertools.groupby by sorting on the same key first.
from itertools import groupby -
Suggest the closest valid option when someone mistypes a command or name.
msg += f", did you mean {hint[0]!r}?" -
Turn ISO 8601 timestamps from logs and APIs into datetime objects without strptime.
from datetime import datetime, timezone -
Compare floating point numbers safely instead of trusting the double equals sign.
import math -
Group items into lists by a key without checking whether the key exists yet.
from collections import defaultdict -
Test whether an address belongs to a network range without string tricks.
from ipaddress import ip_address, ip_network -
Get a scratch folder that disappears on its own when your code is done with it.
import tempfile, shutil -
Generate random tokens for API keys and passwords with the right kind of randomness.
import secrets -
Split a command line like the shell does, and quote values safely for one.
import shlex -
Get total, used and free bytes for any mount point straight from Python.
import shutil -
Run a shell command from Python, capture its output and fail loudly on errors.
import subprocess -
Add up prices and amounts without floating point rounding errors.
from decimal import Decimal, ROUND_HALF_UP -
Hold the most recent n items of a stream without the list growing forever.
from collections import deque -
Read CSV files by column name instead of counting column positions.
import csv -
Combine default settings with user overrides in one readable expression.
settings = defaults | overrides -
Sort rows on one or more fields without writing a lambda.
from operator import itemgetter -
Raises an error when the lists you zip together don't have the same length.
for name, email in zip(names, emails, strict=True): -
Converts times to Dutch local time with summer and winter time handled for you.
from zoneinfo import ZoneInfo -
Gives each item of a list together with the next one, handy for differences and gaps.
from itertools import pairwise -
Replaces a try/except/pass block for an error you expect and are fine with.
from contextlib import suppress -
Caches the results of a Python function, so repeated calls with the same arguments are instant.
from functools import lru_cache -
Reads a TOML file such as pyproject.toml with the standard library, no extra package.
import tomllib -
Splits any iterable into tuples of a fixed size, with the standard library only.
from itertools import batched -
Generates a random UUID, or a name-based one, straight from the command line on Python 3.12 or newer.
python -m uuid -
Starts a local documentation server for every installed module and opens it in your browser.
python3 -m pydoc -b -
Lists, tests, extracts or creates zip archives with the Python standard library.
python3 -m zipfile -l backup.zip -
Runs SQL against a SQLite file from the python standard library, with no extra tools installed.
python3 -m sqlite3 app.db "SELECT count(*) FROM sqlite_master" -
Switches a script between quiet and verbose logging with an environment variable.
import logging, os -
Generates a matching --no-flag for a boolean option, so users can switch defaults off.
import argparse -
Builds a new path with another extension or filename without touching the disk.
from pathlib import Path -
Walks a directory tree and yields matching files as Path objects, with sizes and text readers attached.
from pathlib import Path -
Gives each dataclass instance its own fresh list or dict instead of a shared default.
from dataclasses import dataclass, field -
Makes a dataclass immutable, hashable and typo-proof with two decorator arguments.
from dataclasses import dataclass
Environments 20
-
Run Python in isolated mode so the current folder and environment can't change imports.
python3 -I -c 'import json; print(json.__file__)' # the real json module -
Stop Python from writing pyc files into read only or shared project folders.
PYTHONDONTWRITEBYTECODE=1 python3 app.py -
Install your own project so edits to the source take effect on the next run.
.venv/bin/python -m pip install -e . -
Make a script check that it's running inside a venv before it installs or changes things.
sys.exit("activate the virtual environment first (source .venv/bin/activate)") -
Run a script inside your package without ModuleNotFoundError on its own imports.
python3 mypkg/cli.py # ModuleNotFoundError: No module named 'mypkg' -
Create a venv that can still see system wide packages like those from apt.
sudo apt install python3-gi -
Run a file of imports and helpers each time you open the interactive Python prompt.
import json, os, re, sys -
See your project's dependency tree and which package pulled in a library.
uv tree --depth 1 -
Keeps the script's own folder off the import path so local files cannot shadow modules.
python -P script.py -
Shows the project name instead of .venv in your shell prompt when a venv is active.
python3 -m venv --prompt . .venv -
Shows where an installed Python package lives and lists all the files it installed.
python3 -m pip show -f requests -
Installs the pip version bundled with Python, offline, if pip is missing from the interpreter.
python -m ensurepip --upgrade -
Prints the module search path, the user base and user site folders, and whether the user site is enabled.
python -m site -
Verifies that the installed packages have the dependencies they need, at compatible versions.
python -m pip check, then fix what it names -
Bundles code and dependencies into one executable file that needs only python installed.
python3 -m zipapp myapp -o tool.pyz -m "cli:main" -p "/usr/bin/env python3" -
Stores a script's dependencies in a comment block so one file runs anywhere with uv.
uv add --script fetch.py requests -
Runs python with extra packages in a disposable environment, without installing them anywhere permanent.
uv run --with requests python -c "import requests; print(requests.__version__)" -
Downloads and manages extra python versions per user, independent of the distribution package.
uv python install 3.12 -
Lists only the top-level packages in an environment, hiding the ones pulled in as dependencies.
python3 -m pip list --not-required -
Creates a virtual environment and upgrades pip in it immediately, so installs start from a current version.
python3 -m venv --upgrade-deps .venv
Debugging and speed 19
-
Watch the exact path a script takes through its code, line by line.
python3 -m trace -t script.py -
Speed up repeated membership checks by turning the lookup list into a set.
known = set(load_known_ids()) # convert once -
Speed up a script that waits on many downloads or API calls with a thread pool.
from concurrent.futures import ThreadPoolExecutor -
Log a caught exception with its full traceback at error level.
log = logging.getLogger(__name__) -
Find the lines of code that allocate the most memory in a Python program.
import tracemalloc -
Print the complete traceback inside an except block without stopping the program.
import traceback -
Know when assert disappears and what to use for checks that must always run.
python3 -O check.py # assert is skipped, delete_everything() runs -
Stop print output from showing up late, or not at all, in containers and pipes.
python3 -u worker.py | tee worker.log -
Read the source of a function or class from the prompt without hunting for the file.
import inspect, textwrap -
Print a big nested dict or API response across lines, keys left in order.
from pprint import pp -
Measure how long a block of code takes with the right clock.
import time -
Enables extra warnings and checks, such as unclosed files, while a script runs.
python -X dev script.py -
Prints the traceback of every thread after a timeout, so a hung script shows where it is stuck.
import faulthandler -
Prints both the expression and its value, so debug output labels itself.
name = "jellyfin" -
Prints how long each imported module took, to find the import that slows down startup.
python -X importtime -c 'import asyncio' 2> imports.txt -
Switches or disables breakpoint() calls without editing the source.
PYTHONBREAKPOINT=0 python3 app.py -
Runs a script and then keeps the interpreter open so you can inspect its state.
python3 -i script.py -
Profiles a whole script with the standard library and sorts functions by time spent.
python3 -m cProfile -s cumtime script.py | head -20 -
Makes python raise warnings as errors, so deprecations fail loudly during development.
python3 -W error script.py
Testing 14
-
Wrap the expected number in pytest.approx so tiny float errors do not fail the test.
import pytest -
Stop a pytest run after a set number of failures instead of waiting for the whole suite.
pytest --maxfail=2 -
Mark a failing test as xfail so it is reported but does not fail the suite.
import pytest -
Replace a slow or flaky dependency with a fake during a test.
from unittest.mock import patch -
Assert on stdout and stderr output of a function inside a pytest test.
def greet(name): -
Run only the tests whose names match a keyword expression.
python3 -m pytest -k "login and not bad" -v -
Test code that reads environment variables without leaking the change into other tests.
import os -
Test code that writes files without touching real folders or cleaning up yourself.
def save_report(folder, text): -
Test a function with many inputs without copying the test function.
import pytest -
Make sure code fails with the right exception and the right reason.
import pytest -
Runs the >>> examples in a module's docstrings and reports any whose output no longer matches.
def to_gb(size_bytes): -
Drops into the python debugger at the first test failure so you can inspect variables.
python3 -m pytest -x --pdb tests/test_api.py -
Prints the slowest phases of a test run so you know where the time goes.
python3 -m pytest --durations=5 -
Reruns just the previously failing tests, or runs them first, so feedback arrives in seconds.
python3 -m pytest --lf
Python one-liners 7
-
Print the operating system, kernel and architecture of a machine in one command.
python3 -m platform -
Encode or decode base64 from the terminal without worrying which base64 tool is installed.
echo 'dXNlcjpwYXNz' | python3 -m base64 -d -
Compress or decompress a gzip file with Python when you want the source kept.
python3 -m gzip --best access.log # writes access.log.gz, keeps access.log -
Total a list of numbers from another command without awk or a spreadsheet.
printf '12.5\n3\n4.25\n' | python3 -c 'import sys; print(sum(float(l) for l in sys.stdin if l.strip()))' -
Runs a snippet many times and prints the best average time, so you can compare two ways to do something.
python3 -m timeit "sum(range(1000))" -
Shares a folder over your network with one line of Python, no setup needed.
python3 -m http.server 8000 -
Takes messy one-line JSON and prints it indented, so you can read it and spot typos.
curl -s https://example.com/api | python3 -m json.tool
Build and system 1
-
Compiles every Python file in a folder and reports files with syntax errors.
python -m compileall -q src/
Nothing in this filter yet.