Python Complete Cheatsheet Pack
The Python reference you'll actually keep open. This pack covers Python 3.10+ syntax from basics to advanced — data structures, comprehensions, decorators, context managers, async/await, type hints, pattern matching, and the stdlib modules you use every day. Every section includes runnable examples, common pitfalls, and performance notes. Built for developers who know Python but can't remember the exact syntax for dataclasses vs NamedTuple at 2 AM.
What's Included
- Core Syntax Reference — Variables, operators, f-strings, match/case, walrus operator
- Data Structures — Lists, dicts, sets, tuples, deque, defaultdict, Counter, heapq
-
Comprehensions & Generators — List/dict/set comprehensions, generator expressions,
yield from -
Decorators & Context Managers — Writing decorators,
@functools.wraps,contextlib,__enter__/__exit__ -
Type Hints Guide — Basic types, generics,
Protocol,TypeVar,Literal,TypeGuard -
Async/Await Patterns —
asyncioevent loop, tasks, gather, semaphores, async generators - Standard Library Highlights — pathlib, itertools, functools, collections, dataclasses, logging, re
- Common Patterns — Singleton, factory, observer, retry logic, configuration management
Preview / Sample Content
Match/Case — Structural Pattern Matching (3.10+)
def handle_command(command: dict) -> str:
match command:
case {"action": "create", "name": str(name)}:
return f"Creating {name}"
case {"action": "delete", "id": int(id_)} if id_ > 0:
return f"Deleting item {id_}"
case {"action": "list", "filter": {"status": status}}:
return f"Listing items with status={status}"
case {"action": str(action)}:
return f"Unknown action: {action}"
case _:
return "Invalid command format"
# Match on type and structure
def process(value: object) -> str:
match value:
case int(n) if n > 0: return "positive int"
case int(n) if n < 0: return "negative int"
case str(s) if len(s) > 0: return "non-empty string"
case [x, y]: return f"two-element list: {x}, {y}"
case [x, *rest]: return f"list starting with {x}"
case _: return "something else"
Decorators — Patterns You'll Actually Use
import functools
import time
import logging
from typing import Callable, TypeVar, ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
# Timing decorator
def timer(func: Callable[P, T]) -> Callable[P, T]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
logging.info(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
# Retry decorator with exponential backoff
def retry(max_attempts: int = 3, base_delay: float = 1.0):
def decorator(func: Callable[P, T]) -> Callable[P, T]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
delay = base_delay * (2 ** attempt)
time.sleep(delay)
raise RuntimeError("Unreachable")
return wrapper
return decorator
# Cache with TTL (stdlib only)
def ttl_cache(seconds: int = 300):
def decorator(func: Callable[P, T]) -> Callable[P, T]:
cache: dict[str, tuple[float, T]] = {}
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
key = str(args) + str(kwargs)
if key in cache and time.time() - cache[key][0] < seconds:
return cache[key][1]
result = func(*args, **kwargs)
cache[key] = (time.time(), result)
return result
return wrapper
return decorator
Data Structures — When to Use What
from collections import defaultdict, Counter, deque
from dataclasses import dataclass, field
# Counter — frequency counting in one line
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
counts.most_common(2) # [('apple', 3), ('banana', 2)]
# defaultdict — no more KeyError checks
graph: dict[str, list[str]] = defaultdict(list)
graph["a"].append("b") # No need to check if "a" exists
# deque — O(1) append/pop from both ends
queue: deque[str] = deque(maxlen=100)
queue.append("task1") # Add right
queue.appendleft("urgent") # Add left
queue.popleft() # Remove left: O(1) vs list.pop(0): O(n)
# dataclass — the modern way to define data containers
@dataclass(frozen=True, slots=True)
class Config:
host: str = "localhost"
port: int = 8080
debug: bool = False
tags: list[str] = field(default_factory=list)
Quick Reference Table
| Feature | Syntax | Example |
|---|---|---|
| f-string | f"{expr}" |
f"Hello, {name!r}" |
| Walrus operator | := |
if (n := len(data)) > 10: |
| Unpacking |
*args, **kwargs
|
first, *rest = items |
| Ternary | x if cond else y |
status = "ok" if code == 200 else "fail" |
| Dict merge | `d1 \ | d2` |
| Type union | `X \ | Y` |
| Match/case | match val: |
case {"key": value}: |
| Exception groups | ExceptionGroup |
except* ValueError as eg: |
slots=True |
dataclass arg | 20-35% less memory |
functools.cache |
Unlimited memoize |
@cache on pure functions |
Comparison: Data Container Types
| Feature | dict | dataclass | NamedTuple | TypedDict |
|---|---|---|---|---|
| Mutable | Yes | Configurable | No | Yes |
| Type Hints | Manual | Built-in | Built-in | Built-in |
| Default Values | Yes | Yes | Yes | N/A |
| Hashable | No | If frozen | Yes | No |
| Memory | Higher | Lower (slots) | Lowest | dict-based |
| Inheritance | N/A | Yes | Limited | Yes |
| JSON-friendly | Yes | Needs asdict() | Needs _asdict() | Yes |
| Best For | Dynamic data | Domain objects | Immutable records | API shapes |
Usage Tips
- Start with the data structures decision page — choosing the right container is half the battle.
- Copy the decorator templates — the retry, timer, and cache decorators work in every project.
- Master comprehensions — the cheatsheet shows list, dict, set, and nested comprehensions side by side.
- Use the type hints guide when adding types to existing code — it covers the tricky cases like callbacks, generics, and overloads.
-
Print the stdlib highlights page —
pathlib,itertools, andfunctoolsreplace dozens of pip packages.
This is 1 of 11 resources in the Cheatsheet Reference Pro toolkit. Get the complete [Python Complete Cheatsheet Pack] with all files, templates, and documentation for $15.
Or grab the entire Cheatsheet Reference Pro bundle (11 products) for $79 — save 30%.
Top comments (0)