PCPP1 cheat sheet
PCPP1 · Keep the key ideas within reach.
Advanced OOP
Special methods map syntax to behavior: len for len(), getitem for indexing, iter/next for iteration, contains for 'in', enter/exit for 'with', call for instance(), repr vs str for repr() vs str().
Instance creation order: new(cls, ...) constructs and returns the instance, then init(self, ...) initializes it; init must return None, and returning anything else raises TypeError.
Method resolution order is C3 linearization: a class's MRO is the class, then its bases merged depth-first with ordering preserved and no duplicates; inspect it with ClassName.mro or ClassName.mro().
super() with no arguments works only inside a method body, resolving the next class after the current one in type(self).mro, so it follows the instance's MRO rather than the defining class's.
Descriptors: an attribute whose class defines get (and optionally set/delete) is a descriptor; data descriptors (with set) take precedence over instance dict, non-data descriptors do not.
Abstract base classes: subclass abc.ABC and decorate methods with @abstractmethod; instantiating a subclass that leaves any abstract method unimplemented raises TypeError.
Class body namespace rules: methods do not see class-level names as bare names (no implicit class scope), so refer to them via self or the class name; nested classes do not create enclosing scopes for methods.
Multiple inheritance pitfalls: the diamond problem is handled by cooperative super() calls; a base appearing more than once is allowed only if C3 can linearize it, otherwise Python raises TypeError at class creation.
slots declares fixed instance attributes, removes per-instance dict, and blocks assignment to undeclared attributes; a subclass without slots regains a dict.
Best Practices and Standardization
PEP 8 essentials: 4 spaces per indent, snake_case functions/variables, CapWords classes, UPPER_CASE constants, two blank lines between top-level definitions, one per method, max line length 79 characters.
PEP 257 docstrings: triple double quotes, one-line summary ending with a period, blank line before further description; accessible at runtime via obj.doc and used by help().
PEP 484/526 typing: annotations are not enforced at runtime; use from future import annotations or string literals for forward references, and typing.get_type_hints() to resolve them.
PEP 20 (Zen of Python): explicit is better than implicit, flat is better than nested, and errors should never pass silently unless explicitly silenced; view with import this.
PEP 8 import order: standard library, then third-party, then local application imports, each group separated by a blank line; wildcard imports (from x import *) are discouraged.
Naming conventions: a single leading underscore marks non-public API, a single trailing underscore avoids keyword clashes (class_), and __name is name-mangled to _ClassName__name.
Comparison and truthiness: define eq together with hash (defining eq sets hash to None), and prefer explicit 'is None' over '== None'.
Context managers and resource safety: use with for files and locks; contextlib.contextmanager turns a generator with one yield into a context manager, and closing()/suppress() cover simple cases.
PEP 8 whitespace: no space before a colon in slices and annotations but one after commas; avoid spaces around = for keyword arguments, use them for annotated defaults.
GUI Programming
Tkinter mainloop() must run on the main thread and blocks until the window closes; widget construction and most widget calls must also happen on that thread.
Geometry managers pack, grid, and place must not be mixed in the same container; grid rows/columns are zero-based and grid_columnconfigure(weight=1) is what makes a column expand.
Tkinter variables (StringVar, IntVar, BooleanVar) require an existing Tk root; use tkinter.TclError-free ordering by creating the root before any Var, or pass master explicitly.
Event binding: bind(event, handler) on a widget receives an event object; bind_all applies globally; event names include , , , , and for resize.
after(ms, callback) schedules work on the Tk event loop and returns an id usable with after_cancel(); it is the standard alternative to threading for periodic UI updates.
ttk widgets (ttk.Button, ttk.Treeview, ttk.Notebook) give themed native look; ttk.Treeview columns are configured via columns= and heading()/column(), while items use insert().
Dialogs: filedialog.askopenfilename() returns a path string or empty string when cancelled; messagebox.showinfo() returns 'ok' - always check for the empty result before use.
Thread-safety rule: worker threads must not call Tk methods directly; communicate via queue.Queue polled by root.after, since Tk is not thread-safe.
Widget lifecycle: destroy() removes a widget permanently, pack_forget()/grid_forget() only unmap it; winfo_children() lists children and winfo_width() reports actual rendered size.
Working with RESTful APIs
HTTP verbs map to CRUD: GET reads (safe, idempotent), POST creates (not idempotent), PUT replaces (idempotent), PATCH partially updates, DELETE removes (idempotent).
Status code families: 2xx success (200, 201 created, 204 no content), 3xx redirect, 4xx client error (400, 401 unauthenticated, 403 forbidden, 404, 429 rate limited), 5xx server error.
requests.get(url, params={...}) URL-encodes query strings; requests.post(url, json=payload) sets Content-Type: application/json and serializes with json.dumps.
response.raise_for_status() raises HTTPError for 4xx/5xx; response.json() parses the body and raises requests.exceptions.JSONDecodeError (a ValueError) on invalid JSON.
Authentication headers: requests.get(url, headers={'Authorization': 'Bearer ' + token}); for HTTP Basic use auth=('user', 'password') instead of building the header manually.
Timeouts: requests has no default timeout, so pass timeout=(connect, read) explicitly; a missing timeout can block a program indefinitely.
Sessions: requests.Session() reuses TCP connections and persists headers/cookies across requests; use it for repeated calls to the same host and close it with a with block.
Pagination patterns: limit/offset query parameters, page/page_size, or a Link header with rel='next'; loop until the returned collection is empty or no next link remains.
REST design: resources are nouns in the path (/users/42/orders), state lives in representations, and statelessness means each request carries its own auth and context.