PCPP1 flashcards
PCPP1 · Build recall with a focused review session.
32 cards. Read the term and the definition here. The deck at the top of this page is optional.
- __new__ vs __init__
- __new__ is a static constructor that creates and returns the instance; __init__ then initializes that instance and must return None. Returning a non-None value from __init__ raises TypeError.
- C3 linearization
- Python's algorithm for computing a class's method resolution order: depth-first merge of base classes preserving local precedence and removing duplicates. Inspect it via ClassName.__mro__ or ClassName.mro().
- super() resolution
- Zero-argument super() looks up the next class after the current one in type(self).__mro__, so it follows the actual instance's MRO, not the class where the method was defined.
- Data descriptor precedence
- A descriptor defining __set__ or __delete__ is a data descriptor and takes precedence over the instance __dict__. A non-data descriptor defining only __get__ is overridden by an instance attribute of the same name.
- Abstract base class instantiation
- A class inheriting abc.ABC with any method still decorated @abstractmethod cannot be instantiated; Python raises TypeError until every abstract method is overridden in a concrete subclass.
- __slots__ effect
- Declaring __slots__ as a tuple of names removes the per-instance __dict__ and blocks assignment to undeclared attributes, saving memory. A subclass that omits __slots__ reintroduces __dict__.
- __eq__ and __hash__
- Defining __eq__ in a class sets __hash__ to None, making instances unhashable. Restore hashability by defining __hash__ consistently with equality, typically hashing the same fields compared.
- Name mangling
- An identifier with two leading underscores and at most one trailing underscore inside a class body is rewritten to _ClassName__identifier, which prevents accidental overriding in subclasses but is not true privacy.
- PEP 8 indentation and lines
- Use four spaces per indentation level and no tabs. Limit lines to 79 characters, use two blank lines around top-level definitions and one blank line between methods inside a class.
- PEP 8 naming conventions
- Modules and functions use snake_case, classes use CapWords, constants use UPPER_CASE. A single leading underscore marks non-public API; a trailing underscore avoids clashes with keywords.
- Docstring conventions
- PEP 257 specifies triple double quotes, a one-line summary ending with a period, and a blank line before extended description. The string is stored in the object's __doc__ attribute.
- Runtime behavior of annotations
- PEP 484/526 type annotations are stored in __annotations__ but never enforced at runtime. Forward references need string literals or from __future__ import annotations, resolved by typing.get_type_hints().
- Import grouping order
- PEP 8 orders imports as standard library, third-party, then local application, each group separated by a blank line. Wildcard imports such as from module import * are discouraged.
- Zen of Python principles
- PEP 20 aphorisms include explicit is better than implicit, flat is better than nested, and errors should never pass silently unless explicitly silenced. Display them by running import this.
- contextlib.contextmanager usage
- Decorating a generator function with contextlib.contextmanager turns it into a context manager: code before yield runs on entry, code after yield runs on exit, and exceptions surface at the yield.
- is None comparison
- PEP 8 requires comparing to None with 'is' or 'is not' rather than ==, because identity testing avoids invoking overloaded equality and is the idiomatic singleton check.
- Tkinter mainloop threading rule
- Tkinter is not thread-safe: the mainloop and widget calls belong on the main thread. Worker threads should post results to a queue.Queue that the main thread polls with after().
- Geometry manager mixing
- Within a single container widget you must use only one geometry manager: pack, grid, or place. Mixing pack and grid in the same master causes Tk to hang or raise an error.
- grid column weight
- grid_columnconfigure(index, weight=n) controls how extra space is distributed among columns; without a positive weight the column does not expand when the window is resized.
- after scheduling
- widget.after(milliseconds, callback) schedules callback on the Tk event loop and returns an identifier; after_cancel(id) cancels it. It is the usual way to run periodic UI updates safely.
- Tkinter variable creation
- StringVar, IntVar, and BooleanVar need an existing Tk root (or explicit master); creating one before any root exists raises a TclError about no default root window.
- Event object attributes
- A Tkinter event handler receives an event with attributes such as widget, x and y, keysym for key presses, num for mouse buttons, and width/height for Configure resize events.
- filedialog return value
- filedialog.askopenfilename() returns the chosen path as a string, or an empty string when the user cancels. Code must test for the empty string before opening the file.
- ttk versus tk widgets
- ttk widgets provide themed, native-looking controls such as ttk.Treeview, ttk.Notebook, and ttk.Progressbar. Classic tk widgets remain available but do not follow the platform theme.
- destroy versus forget
- widget.destroy() permanently removes a widget and its children; pack_forget() or grid_forget() only unmaps it so it can be re-added later with the same geometry options.
- HTTP verb semantics
- GET reads and is safe and idempotent; POST creates and is not idempotent; PUT replaces and is idempotent; PATCH partially updates; DELETE removes and is idempotent.
- Key HTTP status codes
- 200 OK, 201 Created with a Location header, 204 No Content, 400 Bad Request, 401 Unauthorized (missing or bad credentials), 403 Forbidden, 404 Not Found, 429 Too Many Requests, 500 Server Error.
- requests json parameter
- requests.post(url, json=payload) serializes payload to JSON and sets Content-Type application/json. Using data=payload instead sends form-encoded content unless you set the header yourself.
- raise_for_status behavior
- response.raise_for_status() raises requests.exceptions.HTTPError when the status code is 4xx or 5xx and does nothing for 2xx and 3xx, so call it before parsing the body.
- requests timeout default
- requests applies no timeout by default, so a slow server can block forever. Pass timeout=seconds or a (connect, read) tuple to bound how long each request may take.
- requests.Session reuse
- A Session persists cookies and headers and reuses TCP connections across requests to the same host, which is faster for repeated calls. Close it, ideally with a with statement.
- REST pagination patterns
- Common schemes are limit and offset parameters, page and page_size parameters, or a Link response header with rel='next'. Clients loop until a page returns no items or no next link.