Python functions take positional and keyword arguments, with defaults evaluated once at definition time. Classes bundle data and methods; @dataclass writes init/repr/eq for you. Dunder methods (__init__, __str__, __len__) hook language syntax. Prefer composition and small classes over deep inheritance.
This Python cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Args:
def f(a, b=1, *args, c, **kwargs)—*args, keyword-only after*. - Defaults: Never
def f(x=[]). UseNoneand assign a new list inside. - Hints:
def load(id: int) -> dict[str, str]:. - lambda: One expression. Name a
defwhen it is not a one-liner callback. - class:
class User:thendef __init__(self, email: str):. - dataclass:
@dataclassfor bags of fields.frozen=Truefor immutability. - property:
@propertyfor computed attributes. Do not hide expensive I/O there. - self: First parameter of instance methods.
clsfor@classmethod.
Copy-paste examples
Dataclass plus a small method
Dataclasses replace boilerplate __init__. Keep SQL out of the class if you can inject a repository.
from dataclasses import dataclass
@dataclass(frozen=True)
class Item:
sku: str
price: int
qty: int = 1
def line_total(self) -> int:
return self.price * self.qty
def totals(items: list[Item]) -> int:
return sum(i.line_total() for i in items if i.qty > 0)Common mistakes
- Mutable default arguments sharing one list across calls.
- Writing Java-style getters for every field instead of attributes/
@property. - Multiple inheritance mixins that hide where a method comes from.
- Using a class when a function and a dict would have been clearer.
FAQ
- What is BLOGPH0 ? The instance. Python passes it automatically on
obj.method(). You must declare it in thedef.
- classmethod vs staticmethod?
classmethodreceives the class (cls) — good for alternate constructors.staticmethodis a function namespaced on the class with no extra arg.
- Do I need OOP in a Flask app? Not for a 50-line script. Yes for services, models, and testing seams as the app grows.
Related Python cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.