144 commands · 9 cheat sheets · Python

Language and Objects master quick reference

Browse 144 commands from 9 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.

Language and Objects · 16 commands

Python Classes and Dataclasses Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Define a classclass Account: passView examples
Initialize instance statedef __init__(self, owner): self.owner = ownerView examples
Define instance behaviordef deposit(self, amount): self.balance += amountView examples
Define shared stateclass Account: currency = 'USD'View examples
Add an alternate constructor@classmethodView examples
Attach a utility@staticmethodView examples
Expose computed state@propertyView examples
Create a subclassclass Admin(User): passView examples
Delegate through the MROsuper().__init__(name)View examples
Test compatible typeisinstance(user, User)View examples
Generate record methods@dataclassView examples
Create a fresh mutable defaulttags: list[str] = field(default_factory=list)View examples
Emulate immutability@dataclass(frozen=True)View examples
Generate slots@dataclass(slots=True)View examples
Convert fields recursivelypayload = asdict(order)View examples
Copy with changesupdated = replace(item, price=12)View examples

Language and Objects · 11 commands

Python Context Managers Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Manage one resourcewith open(path, encoding='utf-8') as file: data = file.read()View examples
Manage several resourceswith open(source) as src, open(target, 'w') as dst: copy(src, dst)View examples
Return an acquired resourcedef __enter__(self): return self.resourceView examples
Handle exitdef __exit__(self, exc_type, exc, traceback): self.close()View examples
Create from a generator@contextmanagerView examples
Close an objectwith closing(resource) as value: use(value)View examples
Suppress selected errorswith suppress(FileNotFoundError): path.unlink()View examples
Redirect standard outputwith redirect_stdout(buffer): print('captured')View examples
Manage dynamic contextswith ExitStack() as stack: files = [stack.enter_context(open(p)) for p in paths]View examples
Register cleanupstack.callback(cleanup, resource)View examples
Use optional contextmanager = open(path) if path else nullcontext(sys.stdout)View examples

Language and Objects · 17 commands

Python Decorators, Closures, and Callables Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Return a closurereturn innerView examples
Rebind enclosing statenonlocal countView examples
Inspect captured valuesvalues = function.__closure__View examples
Apply a decorator@decoratorView examples
Preserve wrapper metadata@wraps(function)View examples
Reach the wrapped callableoriginal = decorated.__wrapped__View examples
Configure a decorator@repeat(times=3)View examples
Stack decoratorsresult = outer(inner(function))View examples
Make instances callabledef __call__(self, value): return self.prefix + valueView examples
Check callabilitysupported = callable(value)View examples
Bind selected argumentsconfigured = partial(function, fixed_arg, option=value)View examples
Bind arguments on methodsmethod = partialmethod(function, fixed_arg)View examples
Register a type implementation@render.register(str)View examples
Inspect dispatch resolutionimplementation = render.dispatch(value_type)View examples
Memoize bounded results@lru_cache(maxsize=128)View examples
Clear a function cachefunction.cache_clear()View examples
Inspect cache statisticsstats = function.cache_info()View examples

Language and Objects · 18 commands

Python Enums and Symbolic Constants Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Declare an enumclass Color(Enum): RED = 1View examples
Look up by valuemember = Color(1)View examples
Look up by namemember = Color['RED']View examples
Read member metadataname, value = member.name, member.valueView examples
Iterate canonical membersmembers = list(Color)View examples
Declare an aliasCRIMSON = REDView examples
Inspect names including aliasesnames = Color.__members__View examples
Reject duplicate values@uniqueView examples
Generate enum valuesPENDING = auto()View examples
Create string-compatible membersclass Format(StrEnum): JSON = auto()View examples
Create integer-compatible membersclass ExitCode(IntEnum): OK = 0View examples
Declare bit flagsclass Permission(Flag): READ = auto()View examples
Combine flagsaccess = Permission.READ | Permission.WRITEView examples
Test a contained flagallowed = Permission.WRITE in accessView examples
Customize missing-value lookup_missing_ = classmethod(normalize_missing_value)View examples
Add member behaviordef can_retry(self): return self is State.FAILEDView examples
Build an enum dynamicallyLevel = Enum('Level', ['LOW', 'HIGH'])View examples
Verify enum constraints@verify(CONTINUOUS)View examples

Language and Objects · 15 commands

Python Exceptions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Catch one exceptionexcept ValueError: number = 0View examples
Inspect an exceptionexcept ValueError as error: print(error)View examples
Catch related failuresexcept (TypeError, ValueError) as error: print(error)View examples
Use ordered handlersexcept FileNotFoundError: use_default()View examples
Run after successelse: print(value)View examples
Always clean upfinally: resource.close()View examples
Raise an exceptionraise ValueError("quantity must be positive")View examples
Re-raise the current errorexcept OSError: log_failure(); raiseView examples
Chain a domain errorraise ConfigError("invalid port") from errorView examples
Hide incidental contextraise ValueError("unknown user") from NoneView examples
Define a custom exceptionclass ConfigError(Exception): passView examples
Store error contexterror = ValidationError(field="email", message="invalid address")View examples
Convert at a boundaryvalue = int(text)View examples
Use managed cleanupwith open("settings.txt", encoding="utf-8") as file: data = file.read()View examples
Assert an invariantassert total >= 0, "total cannot be negative"View examples

Language and Objects · 19 commands

Python Functions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Define a functiondef greet(name): return f"Hello, {name}!"View examples
Call a functionmessage = greet("Ada")View examples
Set a default valuedef greet(name, punctuation="!"): return f"Hello, {name}{punctuation}"View examples
Pass a keyword argumentmessage = greet(name="Ada", punctuation=".")View examples
Require a positional inputdef ratio(value, total, /): return value / totalView examples
Require a keyword inputdef connect(host, *, timeout=10): return f"{host}:{timeout}"View examples
Create a fresh default listdef collect(value, items=None): items = [] if items is None else items items.append(value) return itemsView examples
Collect positional argumentsdef total(*values): return sum(values)View examples
Collect keyword argumentsdef profile(**fields): return fieldsView examples
Unpack positional valuesresult = total(*[4, 6, 10])View examples
Unpack keyword valuesuser = profile(**{"name": "Ada", "role": "engineer"})View examples
Annotate a functiondef area(width: float, height: float) -> float: return width * heightView examples
Add a docstringdef area(width, height): """Return a rectangle's area.""" return width * heightView examples
Return a valuedef double(number): return number * 2View examples
Return several valuesdef bounds(values): return min(values), max(values)View examples
Pass a callbacklabels = list(map(str.upper, ["draft", "ready"]))View examples
Create a small lambdausers.sort(key=lambda user: user["name"])View examples
Return a closuredef multiplier(factor): return lambda value: value * factorView examples
Wrap a functiongreet = trace(greet)View examples

Language and Objects · 18 commands

Python Object Protocols and Special Methods Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Define developer representationdef __repr__(self): return f'Type({self.value!r})'View examples
Define readable textdef __str__(self): return self.labelView examples
Define truth testingdef __bool__(self): return self.is_readyView examples
Define equalitydef __eq__(self, other): return self.value == other.value if isinstance(other, Type) else NotImplementedView examples
Define hashingdef __hash__(self): return hash((self.first, self.second))View examples
Decline an operationreturn NotImplementedView examples
Define less-than orderingdef __lt__(self, other): return self.value < other.value if isinstance(other, Type) else NotImplementedView examples
Define additiondef __add__(self, other): return type(self)(self.value + other.value)View examples
Define reflected additiondef __radd__(self, other): return type(self)(other + self.value)View examples
Report container lengthdef __len__(self): return len(self._items)View examples
Support indexed accessdef __getitem__(self, key): return self._items[key]View examples
Optimize membershipdef __contains__(self, item): return item in self._itemsView examples
Provide iterationdef __iter__(self): return iter(self._items)View examples
Manage one attributevalue = property(getter, setter)View examples
Handle missing attributesdef __getattr__(self, name): return self.fields[name]View examples
Intercept all instance lookupdef __getattribute__(self, name): return object.__getattribute__(self, name)View examples
Define descriptor readingdef __get__(self, instance, owner=None): return self if instance is None else instance.__dict__[self.name]View examples
Learn the assigned namedef __set_name__(self, owner, name): self.name = nameView examples

Language and Objects · 16 commands

Python Structural Pattern Matching Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Match a literalcase 200:View examples
Capture the subjectcase value:View examples
Ignore the subjectcase _:View examples
Match a fixed sequencecase [command, target]:View examples
Capture remaining itemscase [head, *middle, tail]:View examples
Match a command prefixcase ['deploy', environment, *flags]:View examples
Require mapping keyscase {'event': 'login', 'user': user}:View examples
Capture extra mapping entriescase {'event': kind, **metadata}:View examples
Match class attributes positionallycase Point(0, y):View examples
Match class attributes by namecase Point(x=x, y=0):View examples
Match alternativescase 401 | 403:View examples
Capture across alternativescase ('get', path) | ('delete', path):View examples
Keep a matched valuecase (401 | 403) as status:View examples
Add a guardcase {'score': score} if score >= 80:View examples
Match a symbolic constantcase Status.READY:View examples
Match nested structurescase {'type': 'move', 'point': [x, y]}:View examples

Language and Objects · 14 commands

Python Type Hints, Generics, and Protocols Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Annotate a functiondef total(values: list[float]) -> float: ...View examples
No return valuedef log(message: str) -> None: ...View examples
Union typeidentifier: int | strView examples
Optional valuename: str | None = NoneView examples
Narrow by runtime typeif isinstance(value, str): return value.casefold()View examples
Read-only collection inputdef first(values: Sequence[str]) -> str: ...View examples
Read-only mapping inputdef render(values: Mapping[str, object]) -> str: ...View examples
Callable signaturetransform: Callable[[str], str]View examples
Declare a type aliastype UserId = intView examples
Typed dictionary shapeclass UserRow(TypedDict): ...View examples
Generic type parameterdef first[T](values: Sequence[T]) -> T: ...View examples
Structural protocolclass SupportsClose(Protocol): ...View examples
Runtime protocol check@runtime_checkableView examples
User-defined narrowingdef is_str_list(value: list[object]) -> TypeGuard[list[str]]: ...View examples
CMDMEMO TERMINALREAD ONLY