Courseiva

Python Institute Certified Professional in Python Programming 2 (PCPP2) (PCPP2) (PCPP2) — Questions 151194

194 questions total · 3pages · All types, answers revealed

Page 2

Page 3 of 3

151
Multi-Selecthard

Which THREE of the following are true about Python metaclasses?

Select 3 answers
A.Metaclasses are instances of 'type'
B.A metaclass is defined by inheriting from 'type'
C.They are used to create instances directly
D.They are required for all classes in Python 3
E.They allow modification of the class object during creation
AnswersA, B, E

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'.

152
MCQhard

You need to mock an object that is imported into a module. Which patch strategy correctly replaces the object where it is used?

A.Use a global variable to override the module import.
B.Patch the object at the import location within the module being tested.
C.Patch the object at its definition location.
D.Modify sys.modules directly.
AnswerB

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.

153
Multi-Selecteasy

Which THREE of the following are valid ways to instantiate a process in the multiprocessing module?

Select 3 answers
A.Using the multiprocessing.Queue method.
B.By subclassing multiprocessing.Process.
C.Passing a target function to Process constructor.
D.Using the threading.Thread class.
E.Direct instantiation of multiprocessing.Process.
AnswersB, C, E

Subclassing is a valid design pattern.

Why this answer

Process can be instantiated directly, via target function, or by subclassing.

154
MCQmedium

In the Chain of Responsibility pattern, how does a handler decide whether to pass a request to the next handler?

A.By querying the client for the next handler
B.By calling the next handler's handle method only if it cannot fulfill the request
C.By using an exception to jump to the next handler
D.By returning True from a base handler method
AnswerB

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.

155
MCQhard

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?

A.Use a decorator to delete __dict__ after creation
B.Inherit from the object class exclusively
C.Define a __slots__ sequence attribute
D.Set __dict__ = None in the class body
AnswerC

__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.

156
MCQmedium

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?

A.Inheritance
B.Metaclasses
C.Monkey patching
D.Class decorators
AnswerB

Metaclasses control the creation of the class itself.

Why this answer

Metaclasses, specifically the __new__ method, allow for the modification of class creation.

157
MCQmedium

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?

A.process.join()
B.process.wait()
C.process.terminate()
D.process.close()
E.process.is_alive()
AnswerA

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.

158
MCQhard

When using the MongoDB aggregation framework in PyMongo, which stage should be used to filter documents based on a condition?

A.$group
B.$project
C.$match
D.$filter
AnswerC

$match is the standard filtering stage.

Why this answer

The $match stage is used to filter documents in an aggregation pipeline.

159
MCQmedium

When performing bulk inserts in PyMongo, which method is the most efficient?

A.save
B.Looping insert_one
C.bulk_write
D.insert_many
AnswerD

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.

160
MCQmedium

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?

A.scope='class'
B.scope='function'
C.scope='module'
D.scope='session'
AnswerC

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.

161
MCQhard

You are using SQLAlchemy's relationship() function. What does 'back_populates' achieve?

A.It improves query performance.
B.It synchronizes the two sides of the relationship in Python memory.
C.It automatically cascades deletes.
D.It forces a database level foreign key constraint.
AnswerB

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.

162
MCQhard

What is the result of using a Pipe to communicate between two processes if both processes attempt to write to the same end simultaneously?

A.It raises an exception.
B.The OS serializes the writes automatically.
C.The write blocks until the other finishes.
D.One of the writes is silently dropped.
E.The data may be corrupted or interleaved.
AnswerE

Pipes are not inherently thread-safe for concurrent writes.

Why this answer

Data corruption can occur as the messages may become interleaved or mangled.

163
MCQhard

When implementing a custom application protocol over TCP, how should you handle message framing?

A.Use a unique delimiter or a length prefix header for each message.
B.Rely on recv() returning one complete message at a time.
C.Call sleep() between sends to ensure packet separation.
D.Use UDP instead for automatic framing.
AnswerA

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.

164
MCQeasy

Which built-in function allows you to retrieve an attribute from an object by its string name?

A.fetch()
B.getattribute()
C.access()
D.getattr()
AnswerD

getattr(obj, 'name') returns the value of the attribute.

Why this answer

getattr() is the built-in function to access object attributes dynamically.

165
MCQmedium

You are writing a UDP server. What is the main disadvantage of using UDP for high-volume data transmission compared to TCP?

A.UDP packets are always larger than TCP packets.
B.UDP does not provide delivery guarantees or ordering.
C.UDP requires more handshake overhead.
D.UDP is not supported on all operating systems.
AnswerB

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.

166
MCQmedium

What is the result of using 'unittest.mock.patch.object' instead of 'unittest.mock.patch'?

A.It is faster.
B.It targets an attribute on an object instance.
C.It requires less memory.
D.It cannot be used with context managers.
AnswerB

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.

167
Multi-Selectmedium

Which TWO of the following are valid ways to pass data into a pytest test function?

Select 2 answers
A.Using function arguments that match fixture names
B.Defining global variables in the same file
C.Accessing the 'sys.argv' list
D.Using the 'unittest.TestCase' setup method
E.Using the @pytest.mark.parametrize decorator
AnswersA, E

pytest automatically injects fixtures based on argument names.

Why this answer

Fixtures and parametrization are the standard ways to inject data into pytest functions.

168
Multi-Selectmedium

Which THREE design patterns are considered 'Behavioral' patterns?

Select 3 answers
A.Strategy
B.Proxy
C.Command
D.Observer
E.Singleton
AnswersA, C, D

Strategy is a Behavioral pattern.

Why this answer

Observer, Command, and Strategy are all classic Behavioral patterns.

169
MCQhard

When asserting that a mock was called with specific arguments, which method should be used to verify the call history?

A.mock.assert_called_with()
B.mock.verify_args()
C.mock.check_args()
D.mock.called_with()
AnswerA

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.

170
Multi-Selectmedium

Which TWO of the following are true about the Template Method pattern?

Select 2 answers
A.The base class defines the skeleton of an algorithm
B.It uses inheritance to vary parts of an algorithm
C.It forces the use of multiple inheritance
D.Subclasses are not allowed to override any methods
E.It is a Creational pattern
AnswersA, B

This is the definition of the Template Method.

Why this answer

It provides a skeleton algorithm and allows subclasses to override steps.

171
MCQhard

You are writing a pytest plugin and need to access the command-line options. Which hook should you implement in conftest.py?

A.pytest_configure
B.pytest_runtest_setup
C.pytest_addoption
D.pytest_init
AnswerC

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.

172
Multi-Selecthard

Which THREE of the following are essential properties of a robust State pattern implementation?

Select 3 answers
A.The State interface should be as simple as possible
B.The context should store the current state as a private member
C.Each concrete state must be aware of the context to trigger transitions
D.Every state should be a separate Singleton
E.State transitions must be clearly defined
AnswersB, C, E

The context maintains the current state object internally.

Why this answer

State transitions, clear interface, and context awareness are essential.

173
MCQmedium

What is the purpose of 'pytest.mark.xfail'?

A.To debug a failing test.
B.To force a test to fail.
C.To skip a test temporarily.
D.To allow a known failure to not break the build.
AnswerD

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.

174
MCQmedium

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?

A.pytest.catch(CustomError)
B.assert func() == CustomError
C.with pytest.assert_raises(CustomError):
D.with pytest.raises(CustomError):
AnswerD

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.

175
MCQeasy

Which command-line tool is typically used to inspect the contents of a SQLite database file?

A.mysql
B.mongo
C.sqlite3
D.psql
AnswerC

sqlite3 provides the CLI tool for interaction.

Why this answer

The 'sqlite3' command-line interface is the standard tool to interact with .db files.

176
MCQmedium

You are designing a cross-platform network application. Why is it recommended to use socket.getaddrinfo() instead of socket.gethostbyname()?

A.It caches results to reduce DNS requests.
B.It supports IPv6 and is more portable across different network stacks.
C.It is faster than gethostbyname().
D.It automatically resolves local hostnames.
AnswerB

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.

177
MCQmedium

When using 'unittest.mock.MagicMock', what happens when you access an attribute that hasn't been defined?

A.It returns None.
B.It returns the string 'undefined'.
C.It raises an AttributeError.
D.It returns a new MagicMock instance.
AnswerD

This allows for recursive chaining of mocks.

Why this answer

MagicMock instances automatically create new MagicMock objects when you access previously undefined attributes.

178
MCQeasy

What is the primary reason to use the multiprocessing module instead of the threading module for CPU-bound tasks in Python?

A.Threading cannot handle files.
B.Multiprocessing is faster for I/O.
C.Threading does not support locks.
D.Multiprocessing bypasses the Global Interpreter Lock (GIL).
E.Threading is deprecated.
AnswerD

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.

179
MCQmedium

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?

A.Setting the class variable __instance__ to None in the global scope
B.Implementing a dictionary within the metaclass to cache and return existing instances
C.Overriding the __init__ method of the object class
D.Using the __new__ method of the target class instead of the metaclass
AnswerB

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.

180
MCQmedium

When using SQLAlchemy Declarative Base, how do you define a table name that differs from the class name?

A.Set __tablename__ = 'name'
B.Set __table_name__ = 'name'
C.Map it in the metadata object.
D.Use the 'table' argument in the class definition.
AnswerA

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.

181
Multi-Selecteasy

Which TWO of the following are valid ways to synchronize threads?

Select 2 answers
A.threading.Semaphore
B.threading.ProcessPool
C.threading.Queue
D.threading.Process
E.threading.Lock
AnswersA, E

Semaphores limit concurrent access.

Why this answer

Locks and Semaphores are fundamental threading synchronization primitives.

182
MCQhard

In pytest, how can you dynamically add a marker to a test at runtime?

A.In the __init__ file.
B.In the pytest_collection_modifyitems hook.
C.Using @pytest.mark.add_marker()
D.By calling pytest.add_marker() inside the test.
AnswerB

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.

183
MCQmedium

In pytest, how can you share a fixture across multiple files?

A.Place it in conftest.py.
B.Define it in __init__.py.
C.Use the --shared-fixtures flag.
D.Import it in every file.
AnswerA

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.

184
Multi-Selectmedium

Which THREE of the following socket attributes or methods are relevant to managing socket timeouts?

Select 3 answers
A.socket.settimeout()
B.socket.gettimeout()
C.socket.listen()
D.socket.timeout
E.socket.setblocking()
AnswersA, B, D

Sets the timeout duration.

Why this answer

settimeout() sets the delay, gettimeout() retrieves it, and the socket might raise a timeout exception.

185
Multi-Selectmedium

Which THREE of the following can be used to improve the performance of a Python application?

Select 3 answers
A.Adding more decorators to classes
B.Using cProfile to find bottlenecks
C.Disabling the garbage collector
D.Utilizing C-implemented built-ins instead of loops
E.Replacing slow algorithms with more efficient ones
AnswersB, D, E

Profiling is essential for performance tuning.

Why this answer

Profiling, algorithm optimization, and using built-in C-implemented functions are key strategies.

186
MCQhard

You are implementing the Flyweight pattern to optimize memory usage for a text processor. What is the distinction between 'intrinsic' and 'extrinsic' state?

A.Both are shared, but intrinsic is stored in a database
B.Intrinsic state is shared/immutable, extrinsic is context-dependent
C.Neither state can be changed once the Flyweight is instantiated
D.Intrinsic state is the unique data, extrinsic is the shared data
AnswerB

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.

187
Multi-Selectmedium

Which TWO of the following are common risks when implementing the Singleton pattern in Python?

Select 2 answers
A.Incompatibility with the abc module
B.Excessive subclassing of the Singleton class
C.Race conditions in multi-threaded environments during instantiation
D.Hidden global state dependencies throughout the codebase
E.Increased memory consumption for every instance
AnswersC, D

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.

188
Multi-Selecthard

Which TWO of the following statements about the Python Method Resolution Order (MRO) are true?

Select 2 answers
A.You can inspect MRO using the __mro__ attribute
B.The mro() method returns the linearization of classes
C.MRO applies only to single inheritance
D.MRO is determined by the depth-first search
E.MRO changes randomly at runtime
AnswersA, B

__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.

189
Multi-Selecthard

Which TWO of the following are true about the multiprocessing.Queue object?

Select 2 answers
A.It is safe to use between processes.
B.It allows direct memory access between processes.
C.It is safe to use between threads.
D.It is slower than a standard Python list.
E.It requires an external database to function.
AnswersA, C

Queues are process-safe.

Why this answer

Queues are thread-safe and process-safe, and they use internal locks and pipes.

190
MCQeasy

In SQL, which clause is used to filter results based on a condition after grouping?

A.HAVING
B.WHERE
C.ORDER BY
D.GROUP BY
AnswerA

HAVING is for post-group filtering.

Why this answer

The HAVING clause filters aggregated data, whereas WHERE filters raw data.

191
MCQhard

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?

A.apply()
B.map_async()
C.imap()
D.map()
E.starmap()
AnswerC

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.

192
MCQeasy

In the context of the threading module, what does the daemon flag do when set to True?

A.It increases the thread's priority.
B.It prevents the thread from being interrupted.
C.It allows the thread to be killed by the OS.
D.It causes the thread to exit when the main process exits.
E.It ensures the thread completes before the program exits.
AnswerD

This is the definition of a daemon thread.

Why this answer

Daemon threads exit automatically when the main program finishes.

193
Multi-Selectmedium

Which THREE of the following are benefits of using __slots__?

Select 3 answers
A.Faster attribute access
B.Reduced memory footprint
C.Automatic support for multiple inheritance
D.Automatic serialization
E.Prevention of __dict__ creation
AnswersA, B, E

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.

194
MCQeasy

Which socket method is used to bind a socket to a specific address and port?

A.socket.accept()
B.socket.connect()
C.socket.bind()
D.socket.listen()
AnswerC

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 2

Page 3 of 3

All pages