Python guides
Python guides: typing and packaging in real workspaces. The migration traps, in the order they bite.
-
Python decimal — Decimal, quantize, rounding, and money
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 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 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 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.
-
Python Strings — Slicing, Methods, and f-Strings
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 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 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.
-
Python Modules and Packages — import, Aliases, and __name__
Python modules and packages from the ground up: import loads a module once and binds its name, from-import and aliases shape the names you use, a module you write is an ordinary file, __name__ tells a file whether it was run or imported, the __main__ guard keeps run-only code out of imports, a package is a folder of modules, and the standard library ships as modules such as json.
-
Python Loops and Conditionals — for, while, if, range, and enumerate
Python loops and conditionals from the ground up: if, elif, and else pick a branch, a for loop walks a sequence or a range, a while loop repeats while a test stays true, break leaves a loop early, continue skips one pass, an else clause on a loop runs when no break happened, and enumerate and zip walk two views of a list at once.
-
Python List Comprehensions — Map, Filter, and Nest
Python list comprehensions from the ground up: a comprehension builds a list from a loop and an expression in one line, a trailing if filters the items that reach the list, an if and else in the expression picks a value for every item, two for clauses walk pairs and flatten a matrix, the same shape builds dicts and sets, enumerate and zip feed a comprehension paired values, a comprehension variable stays inside the comprehension, and dropping the brackets makes a generator that sum can read once.
-
Python JSON — dumps, loads, and Files
Python JSON from the ground up: dumps turns a dict into a JSON string and loads parses a string back into Python values, indent and sort_keys and separators control how the text is laid out, a tuple comes back as a list and dict keys come back as strings, dump and load work directly on files, nested dicts and lists read one level at a time, bad text raises JSONDecodeError with a position, and a set raises TypeError until you convert it to a list.
-
Python Generators and Iterators — yield, next, and Lazy Sequences
Python generators and iterators from the ground up: a function with yield produces values one at a time, next and StopIteration drive a generator by hand, a generator expression stays lazy where a list comprehension builds at once, an endless generator is safe under a break, the iterator protocol behind for loops, and yield from for delegating to a second generator.
-
Python Functions — def, Default Arguments, and Functions as Values
Python functions from the ground up: def names a block you can call again, return hands a value back, and a default argument fills in when the caller leaves one out. The guide covers keyword arguments, *args and **kwargs, functions passed as values with lambda, and the mutable default trap where one shared list grows across calls.
-
Python Files — open, read, write, and with
Python file handling from the ground up: open with a mode, write and read text with an explicit encoding, the difference between w, a, and x, reading by line or all at once, why with closes the file even when code fails, pathlib for short reads and writes, and binary mode for bytes that are not text.
-
Python Exceptions — try, except, else, finally, and raise
Python exceptions from the ground up: try marks code that can fail, except catches a specific error type and reads its message, else runs only when nothing failed, finally runs either way, raise starts an error on purpose, a custom exception class names a problem in your own terms, and chaining keeps the original cause.
-
Python Decorators — @ Syntax, Wrapping, and functools.wraps
Python decorators from the ground up: a decorator is a function that takes a function and returns a replacement, the @ line applies it at definition time, a wrapper with args and kwargs passes calls through and returns the result, stacked decorators apply bottom first, a decorator factory takes its own arguments, functools.wraps keeps the original name and docstring, and a class with __call__ holds decorator state.
-
Python Datetime — date, time, timedelta, and Formatting
Python datetime from the ground up: date and datetime hold a calendar day and a clock time as separate fields you can read one by one, timedelta adds and subtracts days and seconds and reports the gap between two moments, strftime formats a value as text and strptime parses text back, a datetime is naive until it carries a tzinfo and astimezone converts an aware value between fixed offsets, replace returns a changed copy, combine joins a date and a time, and fromisoformat and timestamp round-trip a value through text and through seconds.
-
Python Context Managers — with, __enter__, __exit__, and contextlib
Python context managers from the ground up: the with statement runs setup before a block and cleanup after it even when the block fails, a class becomes a manager with __enter__ and __exit__, __exit__ receives any exception and decides whether it spreads, returning true holds the exception in, contextlib.contextmanager builds a manager from one generator function, several managers in one with line exit in reverse order, and ExitStack handles a number of managers known only at run time.
-
Python Collections — Counter, defaultdict, deque, and namedtuple
Python collections from the ground up: Counter counts items and reports a missing key as zero, Counter arithmetic keeps only positive counts while update adds counts in place, defaultdict builds a missing value with a factory so grouping and counting need no key check first, deque adds and removes at both ends and a maxlen deque drops the far end when it fills, and namedtuple gives a tuple named fields, defaults, and a replace method that returns a changed copy.
-
Python Classes and Objects — __init__, Methods, Inheritance, and Dataclasses
Python classes and objects from the ground up: a class bundles data and the methods that work on it, __init__ sets up each new object, self names the current object, class attributes are shared while instance attributes belong to one object, inheritance reuses a parent class, special methods control printing and equality, and dataclasses write the routine parts for you.
-
Python argparse — Arguments, Options, and Subcommands
Python argparse from the ground up: a positional argument arrives as a string, an option takes a default and a short name, the type setting converts a string to an int or a float and a bad value exits with code 2, choices limits an option to a fixed set and required makes an option mandatory, nargs collects a run of values into a list, store_true and count build flags that take no value, and subparsers give one program several commands, each with its own arguments.
-
Python Lists, Dicts, and Sets — The Three Collections You Use Every Day
The three collections every Python program uses: a list that keeps order and grows with append, a dict that finds a value by its key and raises KeyError for a missing one, and a set that drops duplicates and answers membership in one test. Programs print max 95 sorted [79, 88, 92, 95] and unique tags 3 has go: True.
-
Migrating to a uv Workspace: The Traps, in the Order They Bite
Migrate two standalone Python packages into one uv workspace, in the order the failures actually bite: the virtual root, the >=3.13 default, and the flag that does not exist — every error quoted verbatim from uv 0.12.23.
-
Taking a Real Codebase to mypy --strict
Migrate a real 191-line Python script to mypy --strict: the interpreter fix, the annotation pass, the Any elimination, coded ignores, the Protocol decision, and the PEP 695 conversion — every error quoted from the actual runs.