All guides
Every guide, newest first. Browse by topic instead, or read the daily tips and puzzles.
-
Python tomllib — Parse TOML with Loads and Load Python
Python tomllib from the ground up: parse a TOML string with loads and a TOML file opened in binary mode with load, read the value types TOML becomes (string, integer, float, boolean, datetime, date, time, array, and table), walk nested tables and arrays of tables, build structure with dotted keys instead of table headers, write multiline basic and literal strings, use the integer forms (hex, octal, binary, and underscores), and handle the TOMLDecodeError traps and the binary-mode rule.
-
Python configparser — Read INI Files, Sections, and Typed Values Python
Python configparser from the ground up: read an INI string with read_string and a file with read_file, walk sections and the DEFAULT fallback section, read typed values with getint, getfloat, and getboolean plus the fallback argument, expand values with basic and extended interpolation or turn interpolation off, handle the case rules (option names fold to lowercase, section names do not), write a configuration back out with write, and handle the duplicate, missing-header, and missing-key traps plus the silent read of a missing file.
-
Python textwrap — Wrap, Fill, Dedent, Indent, and Shorten Python
Python textwrap from the ground up: wrap a paragraph to a fixed width with wrap and turn the lines back into one string with fill, remove the shared indentation from a block of code or text with dedent, add a prefix to chosen lines with indent and a predicate, cut a long string down to whole words with shorten and its placeholder, control long words, hyphens, and tabs through TextWrapper, build a hanging indent with initial and subsequent indents, and avoid the traps of empty input, a first word longer than the width, and leading spaces that survive the wrap.
-
Python pprint — Format Nested Data with Width, Depth, and Compact Python
Python pprint from the ground up: print nested lists and dicts across readable lines with pprint and take the same text as a string with pformat, control the line width, sort dict keys or keep insertion order with sort_dicts, cut off deep structures with depth, pack short items onto shared lines with compact, hold settings in a PrettyPrinter with a custom indent, add underscores to long numbers, and avoid the traps of long strings that stay on one line and recursive data that cannot be read back.
-
Python zipfile — Create, List, Read, and Extract Python
Python zipfile from the ground up: create an archive with writestr, list its entries with infolist and read each entry size and compression type, read an entry back as bytes with read and check the archive with testzip, add a file from disk with write and control its stored name with arcname, choose between the w, a, and x modes, extract files with extractall and extract, and avoid the missing-name and not-a-zip traps.
-
Python venv — Create, Check, and Use a Virtual Environment Python
Python venv from the ground up: create an environment with the venv module, read the folder it makes and the pyvenv.cfg record inside it, tell an inside interpreter from an outside one with sys.prefix and sys.base_prefix, find the site-packages folder where installs land, use the pip that belongs to the environment, keep system packages out by default, and avoid the no-pip, cross-environment, and renamed-folder traps.
-
Python tempfile — Temporary Files and Folders Python
Python tempfile from the ground up: make a scratch folder with TemporaryDirectory that deletes itself, write a named temporary file with NamedTemporaryFile, use an unnamed TemporaryFile and a memory-first SpooledTemporaryFile, control prefix, suffix, and folder, use the low-level mkstemp and mkdtemp calls with manual cleanup, and read the system temporary folder with gettempdir.
-
Python subprocess — run, Capture, check, and Timeout Python
Python subprocess from the ground up: run a command as a list with run, read the CompletedProcess result and its returncode, pass arguments without a shell, capture stdout and stderr as text, send input to a child, turn a failing exit code into CalledProcessError with check, stop a slow child with timeout, and avoid the missing-program and unchecked-failure traps.
-
Python statistics — mean, median, mode, and spread Python
Python statistics from the ground up: find the center with mean, median, mode, and fmean, use the low, high, and grouped medians, take geometric and harmonic means, measure spread with variance and standard deviation for a population and for a sample, cut data with quantiles, relate two series with covariance, correlation, and linear regression, work with the normal distribution, and handle StatisticsError on empty or short data.
-
Python sqlite3 — Tables, Queries, Parameters, and Transactions Python
Python sqlite3 from the ground up: connect to a memory or file database, create a table and insert rows, read rows back as tuples with SELECT, pass values safely with ? parameters and executemany, update and delete with rowcount, read rows by column name with Row, commit or roll back a transaction with a with block, and avoid the no-match, column-type, missing-column, and string-built query traps.
-
Python shutil — Copy, Move, Archive, and Clean Up Python
Python shutil from the ground up: copy a file's contents with copyfile, copy into a folder with copy and copy metadata with copy2, copy a whole folder tree with copytree, move and rename with move and delete a tree with rmtree, pack and unpack an archive with make_archive and unpack_archive, read disk space with disk_usage and find a program with which, and avoid the same-file, missing-file, and existing-folder traps.
-
Python random — seed, randint, choice, and shuffle Python
Python random from the ground up: fix the sequence with seed, draw floats with random and uniform, draw integers with randint, randrange, and getrandbits, pick items with choice and choices, reorder with shuffle, take a sample without repeats, use counts to sample from repeated copies, draw from gauss, triangular, exponential, and beta distributions, save and restore the generator state, and handle the IndexError and ValueError cases on empty or short input.
-
Python pathlib — Joining Paths, Parts, Glob, and Files Python
Python pathlib from the ground up: build a path with the slash operator, split it into name, stem, suffix, parent, and parts, tell a relative path from an absolute one and watch an absolute segment replace what came before, change a name or suffix with with_name, with_stem, and with_suffix, create folders and read and write whole files, list a folder with iterdir and find files with glob and rglob, rename and delete with rename, replace, and unlink, and handle the missing-file and bad-suffix errors.
-
Python math — sqrt, floor, gcd, and log Python
Python math from the ground up: take square roots with sqrt and isqrt, round down, up, and toward zero with floor, ceil, and trunc, work in integers with gcd, lcm, factorial, comb, and perm, sum floats with fsum and multiply with prod, use log, exp, and hypot, convert angles, compare floats with isclose, and handle domain errors and special values.
-
Python logging — Levels, Handlers, and Formatters Python
Python logging from the ground up: get a named logger with getLogger, set its level so debug and info messages pass or stop, attach a StreamHandler to sys.stdout with a Formatter that names the level and the logger, use basicConfig for the one-call setup, give each handler its own level so a file keeps debug records a console drops, let child loggers inherit a parent level and handler through the dotted name, pass message arguments instead of building strings, log an exception with its traceback, and avoid the root-level and second-basicConfig traps.
-
Python itertools — Count, Chain, Group, and Combine Python
Python itertools from the ground up: make endless streams with count, cycle, and repeat, cut them short with islice, join and filter streams with chain, compress, dropwhile, and takewhile, build running totals with accumulate, group sorted data with groupby, list every pairing with product, permutations, and combinations, and avoid the groupby sorting trap and the used-up iterator trap.
-
Python heapq — heapify, heappush, heappop, and nlargest Python
Python heapq from the ground up: turn a list into a min-heap with heapify, read the smallest item at index zero without removing it, add with heappush and remove with heappop, heappushpop, and heapreplace, order work with priority tuples, take the largest and smallest few with nlargest and nsmallest and a key, merge sorted inputs with merge, and handle the IndexError cases on an empty heap.
-
Python hashlib — Hash Text, Bytes, and Files Python
Python hashlib from the ground up: hash bytes with sha256 and read the hexdigest, encode text before hashing it, feed data in chunks with update, hash a file in blocks without loading it whole, compare the output sizes of md5, sha1, sha256, and sha512, sign a message with hmac and check it with compare_digest, and avoid the text-without-encoding and digest-form traps.
-
Python functools — partial, lru_cache, reduce, and wraps Python
Python functools from the ground up: fix arguments in advance with partial, memoize a function with lru_cache and cache, fold a sequence to one value with reduce, preserve a wrapped function name and docstring with wraps, derive the full set of comparisons with total_ordering, and pick an implementation by type with singledispatch.
-
Python fractions — Fraction, exact ratios, and limit_denominator Python
Python fractions from the ground up: build Fraction values from two integers, a string, a Decimal, and a float, reduce and read the numerator and denominator, add, subtract, multiply, and divide with exact results, compare and sort fractions alongside integers and floats, use limit_denominator to find the simple ratio near a float, and handle the ZeroDivisionError and ValueError cases in a scaled quantity.
-
Python enum — Members, auto, IntEnum, and StrEnum Python
Python enum from the ground up: define members with auto, read name and value, look a member up by value and by name, use StrEnum members as plain text, compare and sort IntEnum members as numbers, handle aliases and the unique check, combine IntFlag permissions with the or operator, build an enum with the functional call, and avoid the traps of ordering, unknown lookups, and a member whose value is zero.
-
Python difflib — Close Matches, Ratios, and Diffs Python
Python difflib from the ground up: measure how alike two texts are with the SequenceMatcher ratio and matching blocks, suggest the closest words with get_close_matches and its cutoff, build a unified diff with file headers and line markers, read an ndiff and restore either side from it, turn a comparison into opcodes that name each delete, replace, and insert, compare word lists instead of characters, and avoid the traps of passing one string where lines belong, missing newline endings, and an empty pair scoring a perfect ratio.
-
Python decimal — Decimal, quantize, rounding, and money Python
Python decimal from the ground up: build Decimal values from strings, integers, and tuples, see why Decimal(0.1) carries the float error with it, set the context precision, round to a stated number of places with quantize, choose among the rounding modes (half even, half up, down, floor, and ceiling), work a priced example with tax and a split total, and handle the InvalidOperation and DivisionByZero cases with localcontext for a scoped precision change.
-
Python dataclasses — Fields, Defaults, and Equality Python
Python dataclasses from the ground up: let the dataclass decorator write the init, repr, and equality methods from annotated fields, give a field a plain default or a default_factory for a list, sort instances with order=True, freeze an instance so it can be hashed and put in a set, compute a field in __post_init__, turn an instance into a dict or tuple with asdict and astuple or copy it with replace, and handle the missing-argument, mutable-default, and field-order errors.
-
Python csv — Reading Rows, DictReader, Writing, and Quoting Python
Python csv from the ground up: read rows as lists with csv.reader, read them as dictionaries with DictReader and the header as field names, write rows with csv.writer and read the exact text back including its line endings, write dictionaries with DictWriter and writeheader, quote fields that hold commas, double quotes, and newlines, switch delimiter and quoting rules with a dialect, and avoid the string-numbers, short-row, long-row, and extra-key traps.
-
Python bisect — bisect_left, bisect_right, and insort Python
Python bisect from the ground up: find the insertion point in a sorted list with bisect_left and bisect_right, tell the two apart on duplicate values, insert in order with insort, search by a key on tuples, assign grades from breakpoints, slice a value range with lo and hi bounds, and avoid the trap of searching a list that is not sorted.
-
Rust Structs and Enums — Named Fields, Variants, and match Rust
Rust structs and enums: a Point struct prints x=3 y=4, a Shape enum carries a radius in one variant and named width and height fields in another, and match prints circle area=12.57 and rect area=12.00. The same guide shows the compiler rejecting a match with a missing arm (error E0004), Option as a built-in enum, and struct update syntax moving a String field (error E0382 when the moved field is read again).
-
Python Strings — Slicing, Methods, and f-Strings Python
Python strings from the ground up: len counts the characters, square brackets pick one character or a slice, a negative index counts from the end, strings cannot be changed in place so every method returns a new string, and f-strings put values into text with control over decimals, padding, and alignment.
-
Python Sorting — sorted, sort, key, and reverse Python
Python sorting from the ground up: sorted returns a new list and leaves the source alone, list.sort sorts in place and returns None, a key function such as len, str.lower, or abs changes what items compare by, a tuple key sorts by two fields at once, reverse flips the order after the key is applied, a sort is stable so equal items keep their input order and two sorts in a row can build a two-field order, sorted accepts any iterable and always returns a list, and items that cannot be compared raise TypeError.
-
Python Regular Expressions — re, search, match, Groups, and Substitution Python
Python regular expressions from the ground up: re.search finds a pattern anywhere in a string and returns a match object or None, match anchors at the start and fullmatch must cover the whole string, groups capture parts of a match by number or by name, findall collects every match and finditer yields match objects with positions, sub replaces matches and split cuts on them, a greedy quantifier takes as much as it can while a lazy one takes as little as possible, and re.compile plus re.escape cover repeated and literal patterns.