PCAP study materials
PCAP study resources

PCAP flashcards

PCAP · 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.

__name__ == "__main__"
True only when the module runs as the main script. When imported, __name__ holds the module's name, so guarded code does not execute on import.
sys.modules cache
A dictionary of already-imported modules. Importing a module a second time returns the cached object instead of re-executing its code.
Package __init__.py
A file marking a directory as a package. It executes on first import, and names bound in it become attributes of the package object.
from x import y
Binds only the name y in the current namespace. The module name x is not bound, so referring to x.y afterwards raises NameError.
Relative import syntax
Leading dots in an import statement: one dot means the current package, two dots the parent. Relative imports fail in a script run directly.
__all__ in a module
A list of names that from module import * will import. If absent, star import takes all names not beginning with an underscore.
finally block guarantee
Code in finally always runs: after normal completion, after a handled or unhandled exception, and even when try or except executes return.
except clause ordering
Clauses are checked top to bottom and the first match handles the exception. Put specific exception classes before general ones like Exception.
try else clause
Runs only when the try block finishes without raising. It must follow all except clauses and precede finally.
Bare except danger
except: catches BaseException subclasses such as KeyboardInterrupt and SystemExit. except Exception: catches ordinary errors but lets those propagate.
raise from chaining
raise NewError() from original sets __cause__ on the new exception and links tracebacks, showing both errors in the output.
Custom exception class
A class inheriting from Exception, directly or indirectly. Matching in except clauses depends on the class, not on the message string.
split() versus split(sep)
With no argument, split uses runs of whitespace and discards empty strings. With an explicit separator, consecutive separators produce empty strings.
String immutability
Strings cannot be changed in place. Methods like upper, replace, and strip return new strings, and item assignment raises TypeError.
str.join requirement
The separator string is placed between elements of the iterable. Every element must be a str, otherwise TypeError is raised.
find versus index
Both search for a substring. find returns -1 when not found, while index raises ValueError, so find suits membership tests.
Slice clamping
Out-of-range slice bounds are clamped to the string length rather than raising errors, and negative indices count back from the end.
f-string format spec
Text after a colon inside braces controls formatting, as in f"{value:.2f}" for two decimals or f"{name!r}" to apply repr.
classmethod versus staticmethod
@classmethod receives the class as cls and can create instances; @staticmethod receives neither self nor cls and behaves like a plain function.
Name mangling
An identifier with two leading underscores and at most one trailing underscore becomes _ClassName__name inside the class body, reducing accidental override.
super() semantics
super() returns a proxy that delegates to the next class after the current one in the instance's MRO, not necessarily the direct parent.
__str__ versus __repr__
str() and print use __str__ for readable output; repr() and the interactive prompt use __repr__, which should ideally recreate the object.
Property setter pattern
@property exposes a method as a read attribute; a companion @name.setter method validates or transforms values on assignment while keeping attribute syntax.
Method resolution order
The linearized order classes are searched for attributes, computed by C3 linearization. Inspect it with ClassName.mro() or ClassName.__mro__.
__init__ versus __new__
__new__ allocates and returns the instance; __init__ then initializes it and must return None. Immutable subclasses often override __new__.
List comprehension scope
In Python 3 the loop variable is local to the comprehension and does not leak, unlike a for loop written at the same level.
Generator expression laziness
Parenthesized comprehensions produce values one at a time on demand, so they use constant memory and can be consumed only once.
Lambda restrictions
A lambda body is a single expression, so it cannot contain statements or assignments. It returns that expression's value implicitly.
Late binding in closures
Closures capture variables by reference. Lambdas created in a loop all see the final value unless bound with a default argument like x=x.
nonlocal declaration
Inside a nested function, nonlocal name allows assignment to a variable of the enclosing function instead of creating a new local one.
File open modes
'r' reads, 'w' truncates then writes, 'a' appends, 'x' creates exclusively and fails if the file exists; adding 'b' selects binary mode.
with statement protocol
The context manager's __enter__ runs on entry and __exit__ on exit, closing the file even when the block raises an exception.