Which THREE of the following are true about Python metaclasses?
In Python, metaclasses are subclasses of 'type'.
Why this answer
Metaclasses are types, they allow modifying class creation, and they are defined by inheriting from 'type'.
194 questions total · 3pages · All types, answers revealed
Page 3 of 3
Which THREE of the following are true about Python metaclasses?
In Python, metaclasses are subclasses of 'type'.
Why this answer
Metaclasses are types, they allow modifying class creation, and they are defined by inheriting from 'type'.
You need to mock an object that is imported into a module. Which patch strategy correctly replaces the object where it is used?
Patching the lookup target ensures the module uses the mock.
Why this answer
You must patch the object in the namespace where it is imported (the destination), not where it is defined, to ensure the replacement takes effect.
Which THREE of the following are valid ways to instantiate a process in the multiprocessing module?
Subclassing is a valid design pattern.
Why this answer
Process can be instantiated directly, via target function, or by subclassing.
In the Chain of Responsibility pattern, how does a handler decide whether to pass a request to the next handler?
The handler checks its own criteria and delegates if necessary.
Why this answer
Each handler evaluates if it can process the request; if not, it calls the successor in the chain.
You have a performance-critical application using heavy objects. You want to reduce memory footprint by preventing the creation of __dict__ for every instance. How should you proceed?
__slots__ explicitly defines the allowed attributes, saving memory by removing the instance-specific dictionary.
Why this answer
Defining __slots__ in a class prevents the creation of __dict__ and __weakref__ for instances, significantly reducing memory usage.
You need to dynamically add methods to a class at runtime. Which mechanism allows you to modify the class object before it is fully constructed?
Metaclasses control the creation of the class itself.
Why this answer
Metaclasses, specifically the __new__ method, allow for the modification of class creation.
You are using the multiprocessing.Process class and notice that child processes are not terminating cleanly. Which method should you call to ensure the main process waits for the child process to complete?
Join() is the correct method to synchronize process completion.
Why this answer
The join() method blocks the calling thread until the process whose join() method is called terminates.
When using the MongoDB aggregation framework in PyMongo, which stage should be used to filter documents based on a condition?
$match is the standard filtering stage.
Why this answer
The $match stage is used to filter documents in an aggregation pipeline.
When performing bulk inserts in PyMongo, which method is the most efficient?
insert_many is optimized for bulk operations.
Why this answer
insert_many is designed to send multiple documents in a single batch to the server.
You are writing a pytest fixture that opens a database connection. Which scope should you use to ensure the connection is created once per module, rather than once per test function?
This runs the fixture setup once per module execution.
Why this answer
The 'scope' argument in the @pytest.fixture decorator controls the lifetime. 'module' scope runs the fixture once per module.
You are using SQLAlchemy's relationship() function. What does 'back_populates' achieve?
It enables bidirectional synchronization in the ORM.
Why this answer
It links two sides of a relationship so that changes in one are reflected in the other via the session's identity map.
What is the result of using a Pipe to communicate between two processes if both processes attempt to write to the same end simultaneously?
Pipes are not inherently thread-safe for concurrent writes.
Why this answer
Data corruption can occur as the messages may become interleaved or mangled.
When implementing a custom application protocol over TCP, how should you handle message framing?
Framing techniques are necessary to parse streams into logical units.
Why this answer
Since TCP is a stream, you must implement a protocol layer (like length-prefixing) to know when one message ends and the next begins.
Which built-in function allows you to retrieve an attribute from an object by its string name?
getattr(obj, 'name') returns the value of the attribute.
Why this answer
getattr() is the built-in function to access object attributes dynamically.
UDP is unreliable, whereas TCP provides reliability features.
Why this answer
UDP provides no guarantee of delivery, order, or congestion control, requiring the application to handle these issues.
What is the result of using 'unittest.mock.patch.object' instead of 'unittest.mock.patch'?
It is specific for patching existing attributes on an object.
Why this answer
patch.object is used to patch a specific attribute on an object, rather than patching an object by its string path.
Which TWO of the following are valid ways to pass data into a pytest test function?
pytest automatically injects fixtures based on argument names.
Why this answer
Fixtures and parametrization are the standard ways to inject data into pytest functions.
Which THREE design patterns are considered 'Behavioral' patterns?
Strategy is a Behavioral pattern.
Why this answer
Observer, Command, and Strategy are all classic Behavioral patterns.
When asserting that a mock was called with specific arguments, which method should be used to verify the call history?
This confirms the arguments of the call.
Why this answer
assert_called_with is the standard method for verifying the most recent call or the specific instance of a call.
Which TWO of the following are true about the Template Method pattern?
This is the definition of the Template Method.
Why this answer
It provides a skeleton algorithm and allows subclasses to override steps.
You are writing a pytest plugin and need to access the command-line options. Which hook should you implement in conftest.py?
This hook is specifically for adding custom command-line options.
Why this answer
pytest_addoption is the hook used to register custom command-line options for the pytest session.
Which THREE of the following are essential properties of a robust State pattern implementation?
The context maintains the current state object internally.
Why this answer
State transitions, clear interface, and context awareness are essential.
What is the purpose of 'pytest.mark.xfail'?
xfail signals that failure is expected.
Why this answer
It marks a test as expected to fail, allowing the build to pass even if the test fails.
You are refactoring a legacy module and want to use 'pytest' to check if a function raises a specific custom exception. Which construct is most idiomatic?
pytest.raises is the correct context manager for exception testing.
Why this answer
The 'pytest.raises' context manager is the standard way to verify that a block of code raises a specific exception type.
Which command-line tool is typically used to inspect the contents of a SQLite database file?
sqlite3 provides the CLI tool for interaction.
Why this answer
The 'sqlite3' command-line interface is the standard tool to interact with .db files.
You are designing a cross-platform network application. Why is it recommended to use socket.getaddrinfo() instead of socket.gethostbyname()?
getaddrinfo is the modern, recommended standard for address resolution.
Why this answer
getaddrinfo() is protocol-agnostic (IPv4/IPv6) and returns structured information suitable for socket creation.
When using 'unittest.mock.MagicMock', what happens when you access an attribute that hasn't been defined?
This allows for recursive chaining of mocks.
Why this answer
MagicMock instances automatically create new MagicMock objects when you access previously undefined attributes.
What is the primary reason to use the multiprocessing module instead of the threading module for CPU-bound tasks in Python?
Each process has its own Python interpreter and its own GIL.
Why this answer
Because of the Global Interpreter Lock (GIL), multiple threads cannot execute Python bytecode simultaneously on multiple cores.
You are implementing a Singleton pattern in Python using a metaclass. Which mechanism ensures that the __call__ method of the metaclass is only executed once for a specific class?
Caching instances in the metaclass's scope allows the __call__ logic to intercept creation and return the singleton.
Why this answer
The metaclass __call__ method controls instance creation. By using a dictionary within the metaclass to store existing instances, you ensure that subsequent calls return the cached instance.
When using SQLAlchemy Declarative Base, how do you define a table name that differs from the class name?
This is the required attribute for table mapping.
Why this answer
The __tablename__ attribute is used to explicitly map a class to a specific table name.
Which TWO of the following are valid ways to synchronize threads?
Semaphores limit concurrent access.
Why this answer
Locks and Semaphores are fundamental threading synchronization primitives.
In pytest, how can you dynamically add a marker to a test at runtime?
This hook provides access to the items and their markers before execution.
Why this answer
The 'pytest_collection_modifyitems' hook allows you to modify the collected tests, including adding markers dynamically.
In pytest, how can you share a fixture across multiple files?
conftest.py is the standard file for shared fixtures.
Why this answer
Placing the fixture in a 'conftest.py' file within a directory makes it available to all test files in that directory and subdirectories.
Which THREE of the following socket attributes or methods are relevant to managing socket timeouts?
Sets the timeout duration.
Why this answer
settimeout() sets the delay, gettimeout() retrieves it, and the socket might raise a timeout exception.
Which THREE of the following can be used to improve the performance of a Python application?
Profiling is essential for performance tuning.
Why this answer
Profiling, algorithm optimization, and using built-in C-implemented functions are key strategies.
You are implementing the Flyweight pattern to optimize memory usage for a text processor. What is the distinction between 'intrinsic' and 'extrinsic' state?
This correctly identifies that intrinsic state is shared and extrinsic is passed in.
Why this answer
Intrinsic state is shared and immutable (stored in the Flyweight), while extrinsic state is unique to the context and passed into the Flyweight's methods.
Which TWO of the following are common risks when implementing the Singleton pattern in Python?
Without locking, two threads could create two instances simultaneously.
Why this answer
Global state and threading issues are the most prominent risks when implementing the Singleton pattern.
Which TWO of the following statements about the Python Method Resolution Order (MRO) are true?
__mro__ stores the calculated resolution order.
Why this answer
MRO uses the C3 linearization algorithm and it can be inspected via the __mro__ attribute or the mro() method.
Which TWO of the following are true about the multiprocessing.Queue object?
Queues are process-safe.
Why this answer
Queues are thread-safe and process-safe, and they use internal locks and pipes.
In SQL, which clause is used to filter results based on a condition after grouping?
HAVING is for post-group filtering.
Why this answer
The HAVING clause filters aggregated data, whereas WHERE filters raw data.
You are using a multiprocessing.Pool. Which method should you use to apply a function to a sequence of items and get the results back in order as they complete?
Imap() yields results as they become available, in order.
Why this answer
imap() returns an iterator that yields results in the order of the inputs.
In the context of the threading module, what does the daemon flag do when set to True?
This is the definition of a daemon thread.
Why this answer
Daemon threads exit automatically when the main program finishes.
Which THREE of the following are benefits of using __slots__?
Attribute access can be faster due to the structure of slots.
Why this answer
__slots__ reduces memory usage, prevents the creation of __dict__, and can potentially speed up attribute access.
Which socket method is used to bind a socket to a specific address and port?
bind() is the correct method for assigning address/port.
Why this answer
The bind() method associates a socket with a specific address and port tuple.
Page 3 of 3
Practice PCPP2 by domain
Target a specific domain to shore up weak areas.