All tags
python
Narrow down
Python125
- Tip
import asyncioPython's asyncio.timeout puts a time limit on a block of awaitsWrap awaits in asyncio.timeout and get a TimeoutError when the time is up.2 Dec 2026 - Tip
from enum import StrEnum, autoPython's StrEnum makes enum members behave like plain stringsStrEnum members are real strings, and auto() gives each one its lowercase name.2 Dec 2026 - Tip
except* ValueError as eg:Python's except* handles each error type inside an ExceptionGroupUse except* to catch some exceptions from a group and leave the others for later.2 Dec 2026 - Tip
import pytestPytest.approx compares floats without the rounding surpriseWrap the expected number in pytest.approx so tiny float errors do not fail the test.2 Dec 2026 - Tip
pytest --maxfail=2pytest --maxfail=2 stops the run after two failuresStop a pytest run after a set number of failures instead of waiting for the whole suite.2 Dec 2026 - Tip
from functools import cached_propertyPython's functools.cached_property computes a value once per objectA cached_property runs its method on first access and then keeps the result on the object.2 Dec 2026 - Tip
from itertools import accumulatePython's itertools.accumulate gives a running total of a listaccumulate yields the running sum, or a running max or product if you pass a function.2 Dec 2026 - Tip
from dataclasses import dataclass, replacePython's dataclasses.replace copies an object with one field changedreplace() makes a new dataclass instance with the fields you name changed.2 Dec 2026 - Tip
match cmd.split():Python's match statement picks apart lists and values by their shapematch and case unpack sequences by shape, with guards and alternatives, from Python 3.10.2 Dec 2026 - Tip
import pytestPytest's xfail marker records a known bug without breaking the runMark a failing test as xfail so it is reported but does not fail the suite.2 Dec 2026 - Tip
urllib3<2Pip install -c caps versions without installing anything extraLimit which version a dependency may get, without adding it to the project.1 Dec 2026 - Tip
python3 -m pip download -r requirements.txt -d ./wheelsPip download collects wheels so you can install without internetFetch packages and dependencies on one machine and install them on another.1 Dec 2026 - Tip
python3 -m pip config set global.timeout 60Pip config set saves an option so you stop typing itWrite pip settings to a config file and check which file holds them.1 Dec 2026 - Tip
python3 -m pip index versions requestsPip index versions lists every release you could installSee available versions of a package before you pin or downgrade.1 Dec 2026 - Tip
python3 -m pip download requests==X.Y.Z --no-deps -d ./pkgsPip require-hashes refuses a download that doesn't matchPin each package to a file hash so a swapped download fails.1 Dec 2026 - Tip
python3 -m pip install --only-binary=:all: numpyPip only-binary stops pip from building packages from sourceFail fast instead of compiling when no prebuilt wheel exists.1 Dec 2026 - Tip
import statisticsPython's statistics module gives you median and percentiles without numpySummarise response times or sizes with median and percentiles using only the standard library.30 Nov 2026 - Tip
python3 -m trace -t script.pypython -m trace -t prints every line as your script runs itWatch the exact path a script takes through its code, line by line.30 Nov 2026 - Tip
python3 -I -c 'import json; print(json.__file__)' # the real json modulepython -I runs a script without your local files or user packages getting inRun Python in isolated mode so the current folder and environment can't change imports.30 Nov 2026 - Tip
python3 -m platformpython -m platform tells you which OS and CPU a machine hasPrint the operating system, kernel and architecture of a machine in one command.30 Nov 2026 - Tip
known = set(load_known_ids()) # convert oncePython checks in on a set thousands of times faster than on a listSpeed up repeated membership checks by turning the lookup list into a set.30 Nov 2026 - Tip
import heapqPython's heapq.nlargest picks the top few without sorting everythingGet the biggest or smallest n items from a large list or a generator.30 Nov 2026 - Tip
from unittest.mock import patchPython's unittest.mock.patch fakes a network call in a testReplace a slow or flaky dependency with a fake during a test.30 Nov 2026 - Tip
PYTHONDONTWRITEBYTECODE=1 python3 app.pyPYTHONDONTWRITEBYTECODE keeps Python from leaving __pycache__ foldersStop Python from writing pyc files into read only or shared project folders.30 Nov 2026 - Tip
import jsonPython's json.dumps(default=str) stops the not serializable errorWrite dates, decimals and paths to a file without a custom encoder class.30 Nov 2026 - Tip
.venv/bin/python -m pip install -e .Python -m pip install -e makes code changes live without reinstallingInstall your own project so edits to the source take effect on the next run.30 Nov 2026 - Tip
from pathlib import PathPython's Path.read_text and write_text replace the open and with boilerplateRead or write a whole small file in one line with pathlib.30 Nov 2026 - Tip
echo 'dXNlcjpwYXNz' | python3 -m base64 -dPython -m base64 -d decodes base64 the same way on every systemEncode or decode base64 from the terminal without worrying which base64 tool is installed.30 Nov 2026 - Tip
from concurrent.futures import ThreadPoolExecutorPython's ThreadPoolExecutor.map runs slow network calls side by sideSpeed up a script that waits on many downloads or API calls with a thread pool.30 Nov 2026 - Tip
def greet(name):Python pytest's capsys lets a test check what your code printedAssert on stdout and stderr output of a function inside a pytest test.30 Nov 2026 - Tip
log = logging.getLogger(__name__)Python's log.exception writes the error message and traceback in one callLog a caught exception with its full traceback at error level.30 Nov 2026 - Tip
import tracemallocPython's tracemalloc shows which lines are eating your memoryFind the lines of code that allocate the most memory in a Python program.30 Nov 2026 - Tip
import hashlibPython's hashlib.file_digest checksums a file without a read loopCompute a SHA256 checksum of a file in one call, even for big files.30 Nov 2026 - Tip
sys.exit("activate the virtual environment first (source .venv/bin/activate)")Python's sys.prefix tells a script whether it runs in a virtual environmentMake a script check that it's running inside a venv before it installs or changes things.30 Nov 2026 - Tip
python3 -m pytest -k "login and not bad" -vpython -m pytest -k picks tests by name with and, or and notRun only the tests whose names match a keyword expression.30 Nov 2026 - Tip
for n, line in enumerate(f, start=1):Python's enumerate(start=1) numbers lines the way humans countNumber items from 1 in a loop without adding one everywhere.30 Nov 2026 - Tip
from itertools import groupbyPython's itertools.groupby only groups neighbours, so sort firstAvoid duplicate groups from itertools.groupby by sorting on the same key first.30 Nov 2026 - Tip
msg += f", did you mean {hint[0]!r}?"Python's difflib.get_close_matches adds a did you mean to your scriptSuggest the closest valid option when someone mistypes a command or name.30 Nov 2026 - Tip
from datetime import datetime, timezonePython's datetime.fromisoformat parses timestamps without a format stringTurn ISO 8601 timestamps from logs and APIs into datetime objects without strptime.30 Nov 2026 - Tip
import mathPython's math.isclose compares floats that look equal but aren'tCompare floating point numbers safely instead of trusting the double equals sign.30 Nov 2026 - Tip
import difflibDifflib.unified_diff shows what a script changed in a config filePrint a diff of two texts from a script, in the same format as git and diff -u.30 Nov 2026 - Tip
import tracebackPython's traceback.print_exc shows the full error and lets the script carry onPrint the complete traceback inside an except block without stopping the program.30 Nov 2026 - Tip
from collections import defaultdictPython's defaultdict(list) groups items without the setdefault danceGroup items into lists by a key without checking whether the key exists yet.30 Nov 2026 - Tip
from ipaddress import ip_address, ip_networkPython's ipaddress module checks if an IP is inside a subnetTest whether an address belongs to a network range without string tricks.30 Nov 2026 - Tip
python3 -O check.py # assert is skipped, delete_everything() runspython -O removes assert statements, so never use them for real checksKnow when assert disappears and what to use for checks that must always run.30 Nov 2026 - Tip
import tempfile, shutilPython's tempfile.TemporaryDirectory cleans up after itselfGet a scratch folder that disappears on its own when your code is done with it.30 Nov 2026 - Tip
python3 -u worker.py | tee worker.logpython -u shows print output right away in Docker and pipesStop print output from showing up late, or not at all, in containers and pipes.30 Nov 2026 - Tip
python3 mypkg/cli.py # ModuleNotFoundError: No module named 'mypkg'python -m package.module runs a file so its package imports workRun a script inside your package without ModuleNotFoundError on its own imports.30 Nov 2026 - Tip
import secretsPython's secrets module makes tokens that are safe to use as passwordsGenerate random tokens for API keys and passwords with the right kind of randomness.30 Nov 2026 - Tip
sudo apt install python3-giA python venv with system site packages reuses what your OS already installedCreate a venv that can still see system wide packages like those from apt.30 Nov 2026 - Tip
import inspect, textwrapPython's inspect.getsource shows the code behind any functionRead the source of a function or class from the prompt without hunting for the file.30 Nov 2026 - Tip
import osPython pytest's monkeypatch.setenv changes an env var for one test onlyTest code that reads environment variables without leaking the change into other tests.30 Nov 2026 - Tip
def save_report(folder, text):Python pytest's tmp_path gives every test its own empty folderTest code that writes files without touching real folders or cleaning up yourself.30 Nov 2026 - Tip
import pytestPython pytest.mark.parametrize runs one test against a table of casesTest a function with many inputs without copying the test function.30 Nov 2026 - Tip
import json, os, re, sysPYTHONSTARTUP loads your own helpers into every Python promptRun a file of imports and helpers each time you open the interactive Python prompt.30 Nov 2026 - Tip
python3 -m gzip --best access.log # writes access.log.gz, keeps access.logpython -m gzip compresses a file and keeps the originalCompress or decompress a gzip file with Python when you want the source kept.30 Nov 2026 - Tip
import shlexPython's shlex.split and shlex.quote handle shell quoting for youSplit a command line like the shell does, and quote values safely for one.30 Nov 2026 - Tip
from pprint import ppPython's pprint.pp prints nested data so you can actually read itPrint a big nested dict or API response across lines, keys left in order.30 Nov 2026 - Tip
import shutilPython's shutil.disk_usage reads free disk space without parsing dfGet total, used and free bytes for any mount point straight from Python.30 Nov 2026 - Tip
printf '12.5\n3\n4.25\n' | python3 -c 'import sys; print(sum(float(l) for l in sys.stdin if l.strip()))'A python -c one-liner adds up a column of numbers from a pipeTotal a list of numbers from another command without awk or a spreadsheet.30 Nov 2026 - Tip
import subprocessPython's subprocess.run with check=True stops on a failed commandRun a shell command from Python, capture its output and fail loudly on errors.30 Nov 2026 - Tip
import timePython's time.perf_counter is the clock for timing a piece of your codeMeasure how long a block of code takes with the right clock.30 Nov 2026 - Tip
from decimal import Decimal, ROUND_HALF_UPPython's decimal.Decimal keeps money sums exactAdd up prices and amounts without floating point rounding errors.30 Nov 2026 - Tip
from collections import dequePython's deque(maxlen=n) keeps only the last n lines, like tailHold the most recent n items of a stream without the list growing forever.30 Nov 2026 - Tip
import csvPython's csv.DictReader gives you each row as a dict keyed by the headerRead CSV files by column name instead of counting column positions.30 Nov 2026 - Tip
uv tree --depth 1uv tree shows why a python package is in your projectSee your project's dependency tree and which package pulled in a library.30 Nov 2026 - Tip
import pytestPython pytest.raises(match=) checks the error message, not just the typeMake sure code fails with the right exception and the right reason.30 Nov 2026 - Tip
settings = defaults | overridesPython's dict merge operator | layers defaults and overridesCombine default settings with user overrides in one readable expression.30 Nov 2026 - Tip
import json, os, tempfileOs.replace swaps in a new file in one step, on every platformWrite a file safely by writing a temp copy first and then replacing the original.30 Nov 2026 - Tip
from operator import itemgetterPython's operator.itemgetter sorts a list of dicts on two keysSort rows on one or more fields without writing a lambda.30 Nov 2026 - Tip
python -X dev script.pypython -X dev turns on extra runtime checksEnables extra warnings and checks, such as unclosed files, while a script runs.28 Nov 2026 - Tip
python -P script.pypython -P stops the script directory from landing on sys.pathKeeps the script's own folder off the import path so local files cannot shadow modules.28 Nov 2026 - Tip
python -m compileall -q src/python -m compileall for a quick syntax check of a whole projectCompiles every Python file in a folder and reports files with syntax errors.28 Nov 2026 - Tip
from collections import CounterCollections.Counter.most_common for counting thingsCounts items in any list and returns the most frequent ones.28 Nov 2026 - Tip
import shutilShutil.which checks if a command exists before you call itReturns the full path of a command, or None when it is not installed.28 Nov 2026 - Tip
from contextlib import chdirContextlib.chdir changes directory and always changes backTemporarily changes the working directory for a block and restores it afterwards.28 Nov 2026 - Tip
from graphlib import TopologicalSorterGraphlib.TopologicalSorter orders tasks by their dependenciesSorts items so every one comes after the things it depends on.28 Nov 2026 - Tip
import faulthandlerFaulthandler.dump_traceback_later shows where a script hangsPrints the traceback of every thread after a timeout, so a hung script shows where it is stuck.28 Nov 2026 - Tip
from textwrap import dedentTextwrap.dedent keeps indented multi-line strings tidyStrips shared indentation from a multi-line string so it can sit in indented code.28 Nov 2026 - Tip
>>> 'Arthur: three!'.lstrip('Arthur: ')Str.removeprefix instead of lstrip for a prefixRemoves an exact prefix from a string, unlike lstrip which strips a set of characters.28 Nov 2026 - Tip
python3 -m venv --prompt . .venvpython -m venv --prompt . shows the project name instead of (.venv)Shows the project name instead of .venv in your shell prompt when a venv is active.27 Nov 2026 - Tip
for name, email in zip(names, emails, strict=True):Zip(strict=True) makes Python complain when two lists differ in lengthRaises an error when the lists you zip together don't have the same length.27 Nov 2026 - Tip
from zoneinfo import ZoneInfoPython's zoneinfo gets Dutch summer and winter time right without pytzConverts times to Dutch local time with summer and winter time handled for you.27 Nov 2026 - Tip
python3 -m random pizza sushi pasta "leftovers again"python -m random picks a winner, a number or a dice roll from the terminalPicks a random word, whole number or decimal straight from the terminal, no script needed.27 Nov 2026 - Tip
export PIP_REQUIRE_VIRTUALENV=truePIP_REQUIRE_VIRTUALENV stops pip from installing outside a virtual environmentMakes pip refuse to install packages unless a virtual environment is active.27 Nov 2026 - Tip
python3 -m pip show -f requestsPip show -f lists every file a Python package put on your diskShows where an installed Python package lives and lists all the files it installed.27 Nov 2026 - Tip
from itertools import pairwisePython's itertools.pairwise walks a list in overlapping pairsGives each item of a list together with the next one, handy for differences and gaps.26 Nov 2026 - Tip
from contextlib import suppressPython's contextlib.suppress ignores one expected error in a single lineReplaces a try/except/pass block for an error you expect and are fine with.26 Nov 2026 - Tip
def to_gb(size_bytes):Python's doctest turns the examples in your docstrings into testsRuns the >>> examples in a module's docstrings and reports any whose output no longer matches.26 Nov 2026 - Tip
from functools import lru_cachePython's functools.lru_cache remembers results so slow functions run onceCaches the results of a Python function, so repeated calls with the same arguments are instant.26 Nov 2026 - Tip
import tomllibPython's tomllib reads TOML config files without installing anythingReads a TOML file such as pyproject.toml with the standard library, no extra package.26 Nov 2026 - Tip
from itertools import batchedItertools.batched splits a list into chunks of nSplits any iterable into tuples of a fixed size, with the standard library only.25 Nov 2026 - Tip
python -m ensurepip --upgradepython -m ensurepip installs pip when your Python has noneInstalls the pip version bundled with Python, offline, if pip is missing from the interpreter.25 Nov 2026 - Tip
python -m sitepython -m site shows sys.path and the user site-packages folderPrints the module search path, the user base and user site folders, and whether the user site is enabled.25 Nov 2026 - Tip
python -m uuidpython -m uuid prints a fresh UUID without writing any codeGenerates a random UUID, or a name-based one, straight from the command line on Python 3.12 or newer.25 Nov 2026 - Tip
python -m pip check, then fix what it namesPip check finds broken or conflicting dependencies in an environmentVerifies that the installed packages have the dependencies they need, at compatible versions.25 Nov 2026 - Tip
python3 -m calendar -m 4 2027python -m calendar prints a calendar in your terminalPrints a text calendar for a year or month without installing anything.24 Nov 2026 - Tip
python -X importtime -c 'import asyncio' 2> imports.txtpython -X importtime shows which import makes a script start slowlyPrints how long each imported module took, to find the import that slows down startup.24 Nov 2026 - Tip
python3 -m pydoc -bpython -m pydoc -b opens the Python docs of your own installStarts a local documentation server for every installed module and opens it in your browser.24 Nov 2026 - Tip
python3 -m zipfile -l backup.zippython -m zipfile -l lists a zip archive when unzip is missingLists, tests, extracts or creates zip archives with the Python standard library.24 Nov 2026 - Tip
python3 -m zipapp myapp -o tool.pyz -m "cli:main" -p "/usr/bin/env python3"python -m zipapp packs a project into one runnable .pyz fileBundles code and dependencies into one executable file that needs only python installed.24 Nov 2026 - Tip
PYTHONBREAKPOINT=0 python3 app.pyPYTHONBREAKPOINT decides what a python breakpoint() call doesSwitches or disables breakpoint() calls without editing the source.24 Nov 2026 - Tip
python3 -i script.pypython -i script.py leaves you in a prompt with the script's variablesRuns a script and then keeps the interpreter open so you can inspect its state.24 Nov 2026 - Tip
python3 -m sqlite3 app.db "SELECT count(*) FROM sqlite_master"python -m sqlite3 opens a SQLite shell when the sqlite3 binary is missingRuns SQL against a SQLite file from the python standard library, with no extra tools installed.24 Nov 2026 - Tip
python3 -m cProfile -s cumtime script.py | head -20python -m cProfile -s cumtime shows where a script spends its timeProfiles a whole script with the standard library and sorts functions by time spent.24 Nov 2026 - Tip
python3 -W error script.pypython -W error turns every warning into an exceptionMakes python raise warnings as errors, so deprecations fail loudly during development.24 Nov 2026 - Tip
import logging, osPython logging.basicConfig can read the log level from an environment variableSwitches a script between quiet and verbose logging with an environment variable.24 Nov 2026 - Tip
import argparsePython argparse BooleanOptionalAction adds --flag and --no-flag in one lineGenerates a matching --no-flag for a boolean option, so users can switch defaults off.24 Nov 2026 - Tip
from pathlib import PathPython pathlib with_suffix and with_name rename paths without string slicingBuilds a new path with another extension or filename without touching the disk.24 Nov 2026 - Tip
from pathlib import PathPython pathlib rglob finds files recursively without os.walkWalks a directory tree and yields matching files as Path objects, with sizes and text readers attached.24 Nov 2026 - Tip
from dataclasses import dataclass, fieldPython dataclass fields need default_factory for lists and dictsGives each dataclass instance its own fresh list or dict instead of a shared default.24 Nov 2026 - Tip
from dataclasses import dataclassPython dataclass(slots=True, frozen=True) blocks typos and mutationMakes a dataclass immutable, hashable and typo-proof with two decorator arguments.24 Nov 2026 - Tip
python3 -m pytest -x --pdb tests/test_api.pypython -m pytest -x --pdb opens the debugger at the first failing testDrops into the python debugger at the first test failure so you can inspect variables.24 Nov 2026 - Tip
python3 -m pytest --durations=5python -m pytest --durations=5 lists the slowest testsPrints the slowest phases of a test run so you know where the time goes.24 Nov 2026 - Tip
python3 -m pytest --lfpython -m pytest --lf reruns only the tests that failed last timeReruns just the previously failing tests, or runs them first, so feedback arrives in seconds.24 Nov 2026 - Tip
uv add --script fetch.py requestsuv add --script writes python dependencies into the script itselfStores a script's dependencies in a comment block so one file runs anywhere with uv.24 Nov 2026 - Tip
uv run --with requests python -c "import requests; print(requests.__version__)"uv run --with gives a python one-off its own temporary packagesRuns python with extra packages in a disposable environment, without installing them anywhere permanent.24 Nov 2026 - Tip
uv python install 3.12uv python install fetches a python version without touching the systemDownloads and manages extra python versions per user, independent of the distribution package.24 Nov 2026 - Tip
python3 -m pip list --not-requiredpython -m pip list --not-required shows only what you installed yourselfLists only the top-level packages in an environment, hiding the ones pulled in as dependencies.24 Nov 2026 - Tip
python3 -m venv --upgrade-deps .venvpython -m venv --upgrade-deps starts a venv with a current pipCreates a virtual environment and upgrades pip in it immediately, so installs start from a current version.24 Nov 2026 - Tip
python3 -m timeit "sum(range(1000))"python3 -m timeit times a small piece of code for youRuns a snippet many times and prints the best average time, so you can compare two ways to do something.23 Nov 2026 - Tip
python3 -m pip install --dry-run requestsPip install --dry-run shows what pip would installLists the packages pip would install, without installing or changing anything.19 Nov 2026 - Tip
python3 -m http.server 8000python3 -m http.server shares a folder over HTTP in one lineShares a folder over your network with one line of Python, no setup needed.16 Nov 2026 - Tip
curl -s https://example.com/api | python3 -m json.toolpython3 -m json.tool makes ugly JSON readable in one pipeTakes messy one-line JSON and prints it indented, so you can read it and spot typos.1 Nov 2026 - Tip
pip cache dirpip cache dir, info and purge manage the pip download cacheShows the size of pip's local cache and clears it when it gets too big.7 Apr 2026
Git1
Media1
Nothing matches.