Python guides
Python guides: typing and packaging in real workspaces. The migration traps, in the order they bite.
-
Python uuid — uuid4, uuid5, Namespaces, and Parsing
Python uuid from the ground up: generate a random identifier with uuid4, derive a repeatable one with uuid5 and uuid3 from a namespace and a name, read the fields, int, bytes, and hex forms of a UUID, parse strings, bytes, and integers back into equal objects, and use UUIDs as dictionary keys and sorted values.
-
Python tarfile — Create, List, and Extract Tar Archives
Python tarfile from the ground up: build a tar archive in memory with TarInfo and addfile, list members with getmembers, getnames, and getmember, read contents back with extractfile, open plain and compressed archives with the w, w:gz, w:bz2, w:xz, and r:* modes, walk members with next, extract safely with the data filter, and handle the traversal, link, and read errors an untrusted archive can raise.
-
Python struct — Pack and Unpack Binary Data
Python struct from the ground up: pack values into bytes and unpack bytes back with struct.pack and struct.unpack, control byte order, size, and alignment with the @, =, <, >, and ! prefixes and calcsize, use the integer, float, char, string, pad, and Pascal format characters, handle the exact-size unpack error, write into a buffer with pack_into and unpack_from, and reuse a format with the Struct class and iter_unpack.
-
Python shlex — Split, Quote, and Join Shell-Like Strings
Python shlex from the ground up: split a command line with shell-like quoting using shlex.split, compare POSIX and non-POSIX modes, build a command string safely with shlex.quote and shlex.join, drive the shlex lexer class with comments, whitespace_split, and punctuation_chars, and handle the no-closing-quotation error and the single-quote backslash trap.
-
Python calendar — Month, Weekday, and Leap Year
Python calendar from the ground up: find a weekday with calendar.weekday, read a month's first weekday and length with monthrange, test leap years with isleap and leapdays, build week rows with monthcalendar, iterate days and dates with the Calendar class, print a month with TextCalendar, and set the first weekday with setfirstweekday.
-
Python base64 — Encode and Decode Bytes, URL-Safe Text, and Base85
Python base64 from the ground up: encode bytes with b64encode and decode them back, read the padding, switch to the URL-safe alphabet or a custom one, wrap output for email with encodebytes, use the Base32 and Base16 forms, shrink output with Base85 and Ascii85, and handle the validation, padding, and text-input errors.
-
Python urllib.parse — URLs, Queries, and Quoting
Python urllib.parse from the ground up: split a URL into scheme, host, port, path, query, and fragment with urlparse and urlsplit, resolve a relative link with urljoin and its trailing-slash trap, read a query string with parse_qs and parse_qsl, build one with urlencode, quote and unquote text for a URL, rebuild a changed URL with _replace and urlunsplit, and handle the invalid-port errors.
-
Python ipaddress — Networks, Hosts, and Subnets
Python ipaddress from the ground up: build addresses, networks, and interfaces with ip_address, ip_network, and ip_interface, read a network's address, broadcast, netmask, and size, test containment, subnet and supernet a network, work with IPv6 compression and scope, compare and sort addresses, collapse a list of networks, and handle the strict host-bits trap and the invalid-address errors.
-
Python tomllib — Parse TOML with Loads and Load
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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.