Python Classes and Dataclasses Cheat Sheet
Define Python classes, manage instance and class state, add properties and alternate constructors, use inheritance, and model records with dataclasses.
Open cheat sheet7 organized subcategories
Practical language patterns, collections, functions, and tooling.
Choose a focus
53 focused guides grouped by the kind of task you need to complete.
Define functions, classes, protocols, types, control flow, and reusable behavior.
Browse subcategory 9 guidesTransform, combine, and traverse Python collections and iterables.
Browse subcategory 9 guidesRepresent text, numbers, structured data, dates, binary values, and persistent objects.
Browse subcategory 5 guidesSelect, clean, combine, summarize, reshape, and analyze labeled tabular and time-series data.
Browse subcategory 6 guidesBuild command-line tools and work with files, processes, configuration, and archives.
Browse subcategory 5 guidesOrganize, package, test, instrument, and distribute maintainable Python projects.
Browse subcategory 10 guidesCoordinate parallel work, network services, databases, memory, and performance.
Browse subcategory9 cheat sheets
Define functions, classes, protocols, types, control flow, and reusable behavior.
Define Python classes, manage instance and class state, add properties and alternate constructors, use inheritance, and model records with dataclasses.
Open cheat sheetManage files, locks, temporary state, cleanup stacks, and custom resources with with, contextmanager, closing, suppress, and ExitStack.
Open cheat sheetBuild composable Python callables with closures, nonlocal state, metadata-preserving decorators, factories, partial, singledispatch, and callable objects.
Open cheat sheetModel closed sets of Python constants with Enum, StrEnum, IntEnum, Flag, aliases, auto-generated values, validation decorators, and robust lookup behavior.
Open cheat sheetRaise, catch, inspect, chain, and clean up after Python exceptions with specific handlers, else, finally, custom errors, and context managers.
Open cheat sheetDefine, call, document, annotate, and compose Python functions with safe defaults, flexible arguments, callbacks, closures, and decorators.
Open cheat sheetIntegrate Python classes with representation, truth testing, equality, hashing, ordering, container access, descriptors, and attribute lookup protocols.
Open cheat sheetRoute structured Python data with match and case using literals, captures, sequences, mappings, class patterns, OR patterns, AS patterns, guards, and enum constants.
Open cheat sheetAnnotate Python functions, containers, unions, callables, generics, protocols, type guards, aliases, and dataclass-like records without confusing hints with runtime enforcement.
Open cheat sheet9 cheat sheets
Transform, combine, and traverse Python collections and iterables.
Choose efficient Python containers and ordering tools with Counter, defaultdict, deque, ChainMap, namedtuple, heapq, and bisect.
Open cheat sheetTransform, filter, enumerate, pair, group, flatten, and iterate Python data clearly with comprehensions, generator expressions, zip, sorted, and itertools.
Open cheat sheetCreate, read, update, iterate, merge, and safely query Python dictionaries with practical examples.
Open cheat sheetProcess Python data lazily with iter, next, generator expressions, yield, yield from, enumerate, zip, itertools, and consumption-aware pipelines.
Open cheat sheetBuild efficient Python data pipelines with lazy iterators, grouping, combinatorics, reductions, partial application, caching, and operator-based accessors.
Open cheat sheetCreate, access, update, slice, sort, and transform Python lists with practical copy-ready examples.
Open cheat sheetCreate Python sets, test membership, remove duplicates, update values, perform set algebra, compare relationships, and use immutable frozensets.
Open cheat sheetCreate, inspect, slice, normalize, search, replace, split, join, and format immutable Python strings with Unicode-aware examples.
Open cheat sheetWork with immutable tuples, efficient ranges, indexing, slicing, unpacking, comparison, counting, and sequence protocols in Python.
Open cheat sheet9 cheat sheets
Represent text, numbers, structured data, dates, binary values, and persistent objects.
Handle Python binary data safely with bytes, bytearray, memoryview, struct packing, hexadecimal conversion, slicing, and zero-copy buffer techniques.
Open cheat sheetModel dates, aware datetimes, UTC instants, parsing, IANA time zones, daylight-saving transitions, ambiguous times, and elapsed durations in Python.
Open cheat sheetHandle Python numeric precision deliberately with float comparisons, math.fsum, Decimal contexts and rounding, Fraction arithmetic, and statistics.
Open cheat sheetExchange JSON and CSV safely in Python with deterministic encoding, custom types, strict numeric parsing, duplicate detection, streams, dialects, and records.
Open cheat sheetPersist trusted Python objects with pickle and shelve using explicit protocols, custom state, persistent IDs, safe inspection, and disciplined compatibility boundaries.
Open cheat sheetGenerate reproducible simulations and summarize numeric data with random, secrets, and statistics while avoiding bias, invalid assumptions, and precision traps.
Open cheat sheetSearch, validate, capture, iterate, split, replace, and debug text with Python's re module, raw strings, named groups, flags, and bounded patterns.
Open cheat sheetHandle Unicode text correctly in Python with UTF-8, normalization, case folding, grapheme-aware design, codec error policies, and explicit file boundaries.
Open cheat sheetParse, query, stream, modify, and generate XML safely with ElementTree, namespaces, incremental parsing, canonicalization, and security boundaries.
Open cheat sheet5 cheat sheets
Select, clean, combine, summarize, reshape, and analyze labeled tabular and time-series data.
Detect missing values, normalize text, convert dtypes, validate values, and remove duplicate pandas records without hiding data quality problems.
Open cheat sheetCreate, inspect, select, filter, update, sort, and index pandas DataFrames with explicit, Copy-on-Write-safe patterns.
Open cheat sheetSummarize groups, broadcast group statistics, filter groups, and reshape pandas data with pivot, melt, explode, and crosstab.
Open cheat sheetCombine pandas tables with validated joins, provenance indicators, concatenation, index alignment, nearest-key matching, and difference reports.
Open cheat sheetParse timestamps, handle time zones, build date indexes, resample observations, and calculate rolling, expanding, and exponentially weighted metrics.
Open cheat sheet6 cheat sheets
Build command-line tools and work with files, processes, configuration, and archives.
Design testable Python command-line interfaces with argparse positionals, options, subcommands, validation, defaults, help text, and controlled errors.
Open cheat sheetRead TOML and INI configuration safely in Python with typed values, layered defaults, interpolation controls, validation, and version-aware standard-library APIs.
Open cheat sheetWork safely with Python pathlib, text and binary files, directory traversal, globbing, JSON, temporary files, and atomic replacement.
Open cheat sheetHandle Python process signals, graceful shutdown, environment variables, child-process environments, platform differences, and startup configuration safely.
Open cheat sheetRun child processes safely in Python with argument lists, captured text, checked exit codes, timeouts, standard input, environments, and Popen communication.
Open cheat sheetCreate, inspect, stream, and safely extract ZIP and tar archives with Python, plus gzip, bz2, lzma, and zlib compression for files and bytes.
Open cheat sheet5 cheat sheets
Organize, package, test, instrument, and distribute maintainable Python projects.
Use importlib for dynamic imports, installed distribution metadata, package resources, cache invalidation, and entry-point plugin discovery with safe boundaries.
Open cheat sheetConfigure reliable Python logging with hierarchy, handlers, context, exception tracebacks, filters, structured events, and safe operational practices.
Open cheat sheetOrganize Python code with modules, packages, imports, module execution, search paths, public APIs, relative imports, and importlib resources.
Open cheat sheetStructure, build, install, and publish Python projects with isolated environments, pyproject.toml metadata, reproducible dependencies, and safe release workflows.
Open cheat sheetStructure deterministic Python tests with unittest cases, fixtures, subtests, exception assertions, mock patching, autospecs, call verification, and temporary resources.
Open cheat sheet10 cheat sheets
Coordinate parallel work, network services, databases, memory, and performance.
Write structured asynchronous Python with coroutines, tasks, task groups, timeouts, cancellation, queues, synchronization, and safe blocking-work delegation.
Open cheat sheetCoordinate parallel Python work with thread, process, and interpreter executors, futures, ordered maps, completion handling, timeouts, and cancellation.
Open cheat sheetUse Python hashlib, hmac, and secrets correctly for digests, message authentication, secure tokens, password derivation, and constant-time verification.
Open cheat sheetDiagnose Python memory with reference ownership, cyclic garbage collection, weak references, finalizers, tracemalloc snapshots, and practical leak investigation.
Open cheat sheetBuild reliable Python process workers with start methods, pools, queues, pipes, synchronization, managers, shared memory, and safe shutdown.
Open cheat sheetMeasure Python performance responsibly with timeit, cProfile, pstats, tracemalloc, trace hooks, sampling principles, and repeatable experiments.
Open cheat sheetBuild robust Python TCP and UDP clients and servers with address resolution, framing, timeouts, non-blocking sockets, selectors, and safe cleanup.
Open cheat sheetBuild reliable embedded databases with Python sqlite3 connections, parameter binding, transactions, constraints, row factories, savepoints, and online backups.
Open cheat sheetCoordinate Python threads safely with locks, conditions, events, semaphores, barriers, queues, cancellation, and reliable shutdown patterns.
Open cheat sheetBuild standard-library HTTP clients with urllib: requests, query strings, form bodies, headers, timeouts, TLS, errors, proxies, redirects, and safe URL validation.
Open cheat sheet