Courseiva

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

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

Page 1

Page 2 of 3

Page 3
76
MCQmedium

In the Observer pattern, what is the best way to prevent memory leaks when the Subject maintains a list of Observers?

A.Use a global list of observers to manage them centrally
B.Set the Observer list to None after every notification cycle
C.Use the weakref module to store references to the Observers
D.Explicitly call the detach method for every Observer
AnswerC

weakref.ref allows the Subject to notify observers without preventing their garbage collection.

Why this answer

If the Subject maintains strong references to Observers, they cannot be garbage collected. Using weak references allows them to be collected when no longer used elsewhere.

77
Multi-Selecthard

Which THREE are valid cascade options in SQLAlchemy?

Select 3 answers
A.save-update
B.merge
C.select
D.delete
E.join
AnswersA, B, D

Standard cascade.

Why this answer

delete, save-update, and merge are common cascade operations.

78
Multi-Selecteasy

Which THREE of the following are valid ways to send or receive data?

Select 3 answers
A.socket.send()
B.socket.sendall()
C.socket.recv()
D.socket.transfer()
E.socket.push()
AnswersA, B, C

Standard method to send bytes.

Why this answer

recv(), send(), and sendall() are the primary methods for data transfer in Python sockets.

79
Multi-Selectmedium

Which THREE of the following represent ways to synchronize access to shared data in a multi-threaded application?

Select 3 answers
A.threading.Lock
B.threading.System
C.threading.Semaphore
D.threading.Process
E.threading.Event
AnswersA, C, E

Locks provide exclusive access.

Why this answer

Locks, Semaphores, and Events are core tools for controlling access and state between threads.

80
MCQmedium

You are using the subprocess.run() function to execute an external command. Which argument ensures that the command's stdout is captured as a string rather than printed to the console?

A.capture_output=True
B.text=True
C.stdout=True
D.shell=True
E.pipe=True
.redirect=True
AnswerA

This captures standard output and error automatically.

Why this answer

Setting capture_output=True automatically sets stdout and stderr to subprocess.PIPE.

81
MCQeasy

Which magic method is used to define how an object is displayed for developers (for debugging)?

A.__repr__
B.__format__
C.__str__
D.__display__
AnswerA

__repr__ is for developer-focused, unambiguous representation.

Why this answer

__repr__ is the magic method used to provide an unambiguous string representation of an object.

82
MCQeasy

Which keyword is used to raise an exception in Python?

A.trigger
B.throw
C.raise
D.catch
AnswerC

raise is the correct Python keyword.

Why this answer

The raise keyword is used to trigger an exception.

83
MCQmedium

You are designing a class hierarchy where a subclass needs to ensure it calls the constructor of its parent in a multiple inheritance scenario. Which mechanism is the standard Pythonic approach to handle this dynamically?

A.Using super().__init__()
B.Explicitly calling ParentClass.__init__(self)
C.Manually tracking parent states in a registry
D.Using the __init__subclass__ hook
AnswerA

super() correctly traverses the MRO, ensuring all classes are initialized only once.

Why this answer

super() is the standard way to delegate to the next class in the Method Resolution Order (MRO).

84
Multi-Selectmedium

Which TWO of the following pytest command-line options allow for filtering which tests are run?

Select 2 answers
A.-v
B.-m
C.-k
D.-q
E.-s
AnswersB, C

Filters tests by markers.

Why this answer

-k allows filtering by substring and -m allows filtering by markers.

85
Multi-Selectmedium

Which TWO of the following are valid ways to create a generator in Python?

Select 2 answers
A.Defining a function containing the 'yield' keyword
B.Calling the gen() function on a class
C.Using the @generator decorator
D.Using a list comprehension with brackets
E.Using a generator expression with parentheses
AnswersA, E

This defines a generator function.

Why this answer

Generators can be created via generator expressions (using parentheses) or generator functions (using the yield keyword).

86
Multi-Selecthard

Which TWO of the following are common issues when using select.select()?

Select 2 answers
A.It requires root privileges to execute.
B.It is significantly faster than epoll on all platforms.
C.It is inefficient for monitoring thousands of concurrent sockets.
D.It has a limited maximum number of sockets it can monitor.
E.It cannot be used with non-blocking sockets.
AnswersC, D

select has an O(n) performance characteristic that degrades with many sockets.

Why this answer

select is limited by the maximum number of file descriptors (FD_SETSIZE) and is not as efficient as epoll/kqueue for massive numbers of connections.

87
Multi-Selectmedium

Which THREE attributes of 'unittest.mock.Mock' allow for verifying call interactions?

Select 3 answers
A.call_args_list
B.return_value
C.side_effect
D.call_args
E.method_calls
AnswersA, D, E

Stores a list of all call arguments.

Why this answer

call_args, call_args_list, and method_calls provide metadata about how the mock was interacted with during a test.

88
MCQmedium

When using subprocess.Popen, why is it dangerous to use shell=True with user-supplied input?

A.It prevents capturing stderr.
B.It slows down execution significantly.
C.It crashes the Python interpreter.
D.It leads to shell command injection vulnerabilities.
E.It forces the use of hardcoded paths.
AnswerD

Executing arbitrary shell commands is a major security flaw.

Why this answer

It introduces a command injection vulnerability where a user can execute arbitrary shell commands.

89
MCQhard

You are utilizing the Mediator pattern to reduce coupling between components. Which of the following describes the role of the Mediator?

A.It allows components to communicate directly with each other
B.It enforces that components are implemented as Singletons
C.It acts as a central hub that coordinates interactions between components
D.It is responsible for data storage for all components
AnswerC

This is the primary duty of the mediator.

Why this answer

The Mediator centralizes communication between components, so they don't need to refer to each other directly.

90
MCQmedium

You are implementing the Command pattern. How can you best support the 'Undo' operation for a command that changes a document's state?

A.Store the delta or previous state information within the concrete command instance
B.Use the Python 'copy' module to clone the document before every command
C.Store the entire document object in the command history
D.Re-execute the entire command history up to the point of the undo
AnswerA

Storing enough information to reverse the operation is the standard way to implement Undo in the Command pattern.

Why this answer

The Command object must store the previous state or the inverse operation before performing the change, allowing it to revert the state later.

91
MCQeasy

What is the purpose of the socket.recvfrom() method?

A.It retrieves data and the sender's address in a single call.
B.It is for TCP servers to accept new connections.
C.It forces a socket to switch to UDP mode.
D.It is used to receive large files in chunks.
AnswerA

This is essential for UDP, where no permanent connection exists.

Why this answer

recvfrom() is designed for connectionless protocols like UDP to receive data and return the address of the sender.

92
Multi-Selectmedium

Which THREE operations are supported by the PyMongo 'bulk_write' method?

Select 3 answers
A.FindOne
B.DeleteOne
C.UpdateOne
D.InsertOne
E.AggregateOne
AnswersB, C, D

DeleteOne is a valid bulk write operation.

Why this answer

bulk_write handles InsertOne, UpdateOne, and DeleteOne operations.

93
MCQeasy

Which command-line argument shows the values of local variables in the event of a test failure?

A.--debug
B.--showlocals
C.--traceback
D.--locals
AnswerB

This flag is specifically for viewing local variables.

Why this answer

The --showlocals flag instructs pytest to display local variables in the traceback output upon failure.

94
MCQmedium

When spawning processes on Windows, what is the default start method used by the multiprocessing module?

A.thread
B.exec
C.forkserver
D.fork
E.spawn
AnswerE

Spawn is the default on Windows.

Why this answer

The 'spawn' method is the default on Windows.

95
MCQhard

Two threads are modifying a shared global integer. You want to ensure that only one thread modifies the integer at a time. Which synchronization primitive is most appropriate?

A.threading.Lock
B.threading.Event
C.multiprocessing.Semaphore
D.multiprocessing.Queue
E.threading.Condition
AnswerA

A Lock provides the necessary mutual exclusion for threads.

Why this answer

A Lock (or Mutex) is the standard tool to ensure mutually exclusive access to a shared resource.

96
MCQhard

You are using socket.socket(socket.AF_INET, socket.SOCK_DGRAM). You attempt to send 10,000 bytes via sendto(). Why might the operation raise an OSError?

A.The socket must be set to non-blocking mode to send large data.
B.UDP is connection-oriented and requires connect() first.
C.The datagram size exceeds the maximum packet size allowed by the network stack.
D.TCP handshaking is missing for UDP.
AnswerC

OS network buffers have limits; large UDP datagrams may trigger errors if they exceed the MTU or buffer capacity.

Why this answer

UDP packets are limited by the MTU of the network path; trying to send a datagram larger than the buffer/MTU limits can cause an OS-level error.

97
MCQmedium

You need to ensure that a method can be called on the class directly, without requiring an instance. Which decorator should be used?

A.@classmethod
B.@property
C.@abstractmethod
D.@staticmethod
AnswerA

@classmethod receives the class reference.

Why this answer

The @classmethod decorator receives the class as the first argument, allowing factory-style methods.

98
Multi-Selecteasy

Which THREE methods are part of the PEP 249 Python DB-API 2.0 interface?

Select 3 answers
A.get_json
B.commit
C.execute
D.filter_by
E.fetchone
AnswersB, C, E

Standard method on connection.

Why this answer

execute, fetchone, and commit are standard parts of the DB-API specification.

99
Multi-Selectmedium

Which TWO of the following methods are typically used on a TCP server socket?

Select 2 answers
A.socket.listen()
B.socket.sendall()
C.socket.recvfrom()
D.socket.bind()
E.socket.connect()
AnswersA, D

Required to transition the socket to passive mode.

Why this answer

A TCP server uses bind() to assign the address and listen() to prepare for incoming connections.

100
Multi-Selecthard

Which THREE of the following are true about the 'subprocess' module's interaction with the operating system?

Select 3 answers
A.It can connect to standard input/output pipes.
B.It automatically cleans up zombie processes.
C.It allows direct manipulation of the parent process's memory.
D.It can change the current working directory of the child.
E.It can set the environment variables for the child process.
AnswersA, D, E

The stdin/stdout arguments allow this.

Why this answer

Subprocess allows control over pipes, environments, and working directories for child processes.

101
Multi-Selecthard

Which TWO of the following are potential issues when using the 'fork' start method in multiprocessing?

Select 2 answers
A.Threads present in the parent may not be safe in the child.
B.Child processes inherit the parent's file descriptors.
C.It cannot share data at all.
D.It crashes on all Unix systems.
E.It is always slower than spawn.
AnswersA, B

Threads are often broken in the child process after a fork.

Why this answer

Forking a process inherits the parent's memory, which can lead to issues with locks and threads.

102
MCQmedium

Which of the following describes the difference between Process.terminate() and Process.kill()?

A.There is no difference.
B.Terminate() sends SIGTERM, while kill() sends SIGKILL.
C.Terminate() is for threads.
D.Terminate() is more immediate than kill().
E.Kill() is only available on Windows.
AnswerB

SIGTERM allows cleanup, SIGKILL does not.

Why this answer

On most POSIX systems, terminate() sends SIGTERM (polite), while kill() sends SIGKILL (immediate).

103
Multi-Selecthard

Which THREE features are provided by SQLAlchemy's Unit of Work pattern?

Select 3 answers
A.Direct translation of HTTP requests to SQL
B.Identity mapping to ensure object uniqueness
C.Tracking object changes (dirty checking)
D.Flushing changes to the DB in optimal order
E.Automatic creation of tables
AnswersB, C, D

Identity maps keep object uniqueness per session.

Why this answer

The Unit of Work pattern manages changes to objects and ensures they are flushed to the DB in the correct order.

104
Multi-Selectmedium

Which THREE of the following features are common to both the threading and multiprocessing modules?

Select 3 answers
A.The start() method to begin execution.
B.Direct access to the GIL.
C.The join() method to wait for completion.
D.Automatic shared memory.
E.The Lock class for synchronization.
AnswersA, C, E

Both classes use start().

Why this answer

Both modules provide mechanisms for joining, starting, and using locks for synchronization.

105
MCQhard

When handling TCP streams, why might recv(1024) return fewer than 1024 bytes even if the sender sent more?

A.The packet was dropped due to network congestion.
B.TCP is a stream protocol; it does not guarantee message boundaries.
C.The socket was set to non-blocking mode.
D.The OS limited the receive window size.
AnswerB

recv() returns whatever data is currently in the receive buffer, not necessarily the full message.

Why this answer

TCP is a stream-oriented protocol, not a message-oriented one. Data is delivered based on buffer availability and segmentation.

106
Multi-Selecthard

Which THREE of the following are true regarding the use of 'unittest.mock.patch'?

Select 3 answers
A.It automatically deletes the original object.
B.It can be used as a context manager.
C.It can be used as a decorator.
D.It is only available for local modules.
E.It can be manually started and stopped.
AnswersB, C, E

Handy for selective patching.

Why this answer

Patching can be used as a decorator, a context manager, or manually with 'start' and 'stop'.

107
MCQhard

When using select.select(inputs, outputs, exceptions), what does the 'outputs' list signify?

A.Sockets that are ready to send data without blocking.
B.Sockets that are closed for writing.
C.Sockets that have finished writing.
D.Sockets that have received an interrupt signal.
AnswerA

Writing to these sockets will not trigger a block.

Why this answer

The 'outputs' list contains sockets that are monitored for readiness to accept data for writing without blocking.

108
Multi-Selecthard

Which TWO of the following are true about the 'descriptor protocol' in Python?

Select 2 answers
A.Descriptors must be defined inside a metaclass
B.A descriptor is a class that implements __get__, __set__, or __delete__
C.Descriptors are only used for methods
D.Descriptors can be used to customize attribute access
E.Descriptors automatically make an object serializable
AnswersB, D

This is the core definition of the descriptor protocol.

Why this answer

Descriptors define __get__, __set__, or __delete__, and they allow objects to customize attribute access.

109
MCQhard

In SQLAlchemy, how do you prevent an object from being saved to the database during a session.commit()?

A.session.delete(obj)
B.session.detach(obj)
C.session.rollback()
D.session.expunge(obj)
AnswerD

expunge removes the object from the session's persistence management.

Why this answer

You can use session.expunge(obj) to remove the object from the session's management.

110
MCQmedium

You are implementing a Proxy pattern to provide lazy initialization for a resource-heavy object. Which technique is most effective for checking if the real object exists without triggering its constructor prematurely?

A.Use the @property decorator to trigger instantiation immediately upon object creation
B.Overload the __del__ method to release the resource
C.Use a try-except block around the Proxy's constructor
D.Check if the object attribute is None before calling the constructor
AnswerD

Lazy initialization typically uses a check against None to instantiate the heavy object only when accessed.

Why this answer

The Proxy should hold a reference to the real object and only instantiate it when a method is called that requires the real object's functionality.

111
Multi-Selectmedium

Which THREE are characteristics of BSON (Binary JSON) as used by MongoDB?

Select 3 answers
A.It is optimized for efficient traversal
B.It is deprecated in newer MongoDB versions
C.It is exactly the same as JSON
D.It supports more data types than JSON
E.It is binary-encoded
AnswersA, D, E

The binary structure allows for fast parsing.

Why this answer

BSON is binary-encoded, supports more types than JSON, and is optimized for traversal.

112
MCQmedium

You are building an application using SSL/TLS. Which module must be used to wrap a standard socket to provide encrypted communication?

A.cryptography
B.hashlib
C.ssl
D.socket.ssl
AnswerC

The ssl module provides the wrap_socket or context-based wrapping functionality.

Why this answer

The ssl module provides the necessary wrappers to enable TLS/SSL over standard socket objects.

113
MCQmedium

You need to compare two objects for equality based on a custom attribute. Which method should you override?

A.__hash__
B.__identical__
C.__eq__
D.__cmp__
AnswerC

__eq__ implements the equality operator.

Why this answer

The __eq__ magic method defines the behavior of the equality operator (==).

114
MCQmedium

When using 'unittest', how do you ensure that a teardown method runs even if the test method raises an exception?

A.The framework automatically calls tearDown().
B.You must check 'self.failureException'.
C.You must use the 'addCleanup' method.
D.Use a try-finally block inside the test method.
AnswerA

unittest handles this by design after each test method.

Why this answer

The 'tearDown' method is guaranteed to run by the unittest framework regardless of the test outcome, assuming setup succeeded.

115
MCQhard

When using socket.setsockopt(), which option is required to immediately reuse a port that is currently in a TIME_WAIT state after a server restart?

A.socket.TCP_NODELAY
B.socket.SO_REUSEADDR
C.socket.SO_LINGER
D.socket.SO_KEEPALIVE
AnswerB

SO_REUSEADDR prevents EADDRINUSE errors on bind after a quick restart.

Why this answer

SO_REUSEADDR allows a socket to bind to an address/port that is currently in the TIME_WAIT state.

116
MCQmedium

When writing a context manager using the @contextlib.contextmanager decorator, what should the function do to pass a value to the 'as' clause?

A.Assign to a global variable
B.Use the return statement
C.Yield the value
D.Raise an exception
AnswerC

Yielding passes control to the block inside the with statement and provides the value.

Why this answer

The yield statement in a decorated generator function passes the value to the with statement's as target.

117
Multi-Selecteasy

Which THREE of the following are valid address families or socket types used with the Python socket module?

Select 3 answers
A.socket.AF_TCP
B.socket.AF_INET
C.socket.AF_INET6
D.socket.SOCK_LOCAL
E.socket.SOCK_STREAM
AnswersB, C, E

Standard IPv4 family.

Why this answer

AF_INET and AF_INET6 are common address families, while SOCK_STREAM and SOCK_DGRAM are standard socket types.

118
MCQmedium

You are configuring a socket timeout. What happens if you call socket.settimeout(5.0) and the operation exceeds 5 seconds?

A.The socket automatically closes.
B.The operation returns None.
C.The kernel silently drops the connection.
D.A socket.timeout exception is raised.
AnswerD

This is the standard mechanism for handling socket delays.

Why this answer

A timeout sets a limit on blocking operations; if the time is exceeded, a socket.timeout exception is raised.

119
MCQeasy

In pytest, how can you skip a test based on the operating system platform?

A.pytest.ignore_if(platform='win32')
B.pytest.skip_on('win32')
C.@pytest.skip(os='win32')
D.@pytest.mark.skipif(sys.platform == 'win32')
AnswerD

This correctly evaluates the platform condition at collection time.

Why this answer

The @pytest.mark.skipif decorator allows for conditional skipping based on expressions like sys.platform.

120
MCQhard

You are implementing the Visitor pattern to add operations to a set of stable class structures. Why is the 'Double Dispatch' mechanism essential?

A.It prevents the element from needing to know about the visitor
B.It allows the visitor to access private methods of the element
C.It resolves the method call based on the runtime types of both the visitor and the element
D.It allows the visitor to be defined as a singleton
AnswerC

This is the core concept of double dispatch in the Visitor pattern.

Why this answer

Double dispatch ensures that the correct method is executed based on both the type of the Visitor and the type of the Element being visited.

121
Multi-Selecthard

Which TWO of the following are valid ways to implement the Proxy pattern in Python?

Select 2 answers
A.Using the 'import' hook in the sys module
B.Inheriting from the target class and overriding its methods
C.Using a decorator to modify the class structure
D.Changing the global variable scope
E.Using the __getattr__ magic method to intercept property access
AnswersB, E

This is a standard way to implement a virtual or remote proxy.

Why this answer

Proxy can be implemented using class-based wrapping or by overriding magic methods like __getattr__.

122
MCQmedium

You are designing a State pattern. Which component is responsible for changing the state of the context object?

A.The abstract state base class
B.A separate controller object
C.The client code
D.The concrete state objects
AnswerD

Concrete states often define the next state transition, keeping the context clean.

Why this answer

Either the Context or the State objects themselves can transition the state, but encapsulating the transition logic inside the concrete state objects is typical for complex state flows.

123
MCQhard

You are using 'slots' to save memory. What is a significant side effect of defining __slots__ in a class?

A.Methods cannot be defined
B.The class cannot be inherited from
C.Dynamic attribute addition is disabled
D.The class becomes immutable
AnswerC

Instances cannot have attributes assigned outside the defined slots.

Why this answer

Classes with __slots__ do not allow the creation of new attributes dynamically unless '__dict__' is explicitly included in __slots__.

124
MCQmedium

What is the purpose of the 'autospec' argument in 'patch'?

A.It creates a mock with the same API as the original object.
B.It speeds up test execution.
C.It automatically generates a return value.
D.It automatically documents the mock calls.
AnswerA

autospec enforces signature and method existence compliance.

Why this answer

autospec ensures the mock has the same attributes and methods as the object it is replacing, preventing tests from passing when they call non-existent methods.

125
MCQeasy

Which of the following is a valid way to run all tests in a directory using pytest?

A.pytest
B.pytest --all
C.python -m unittest discover
D.pytest --execute-all
AnswerA

By default, pytest executes all discovered tests.

Why this answer

Running 'pytest' without arguments in a directory defaults to discovering and executing all tests in that directory tree.

126
Multi-Selecteasy

Which TWO are common methods to handle BSON Date objects in PyMongo?

Select 2 answers
A.Using bson.datetime.Datetime
B.Using standard Python datetime objects
C.Using the 'timestamp' helper method
D.Using ISODate strings
E.Using the bson.codec_options for custom handling
AnswersB, E

PyMongo handles datetime natively.

Why this answer

datetime.datetime objects are automatically converted to BSON Dates.

127
MCQmedium

You want to store an object in a set. What must the object implement?

A.__iter__
B.__hash__ and __eq__
C.__set__
D.__init__ only
AnswerB

These are the requirements for an object to be hashable.

Why this answer

To be hashable (and thus stored in a set), an object must implement __hash__ and have equality defined via __eq__.

128
MCQeasy

Which Python design principle is most strongly supported by the Adapter pattern?

A.Single Responsibility Principle
B.Dependency Inversion Principle
C.Open/Closed Principle
D.Liskov Substitution Principle
AnswerC

It allows adding functionality (via new adapters) without modifying existing client code.

Why this answer

The Adapter pattern allows incompatible interfaces to work together, promoting the Open/Closed Principle by allowing new adapters without changing existing code.

129
Multi-Selectmedium

Which TWO of the following are components of the Model-View-Controller (MVC) pattern frequently seen in Python web frameworks?

Select 2 answers
A.Strategy
B.Model
C.Facade
D.Observer
E.View
AnswersB, E

The Model handles data logic.

Why this answer

The Model (data) and View (representation) are core, while Controllers or View-models mediate.

130
MCQmedium

Which PyMongo method should be used to update a single document if you want to modify specific fields without replacing the entire document?

A.update_one
B.upsert
C.save
D.replace_one
E.update_many
AnswerA

update_one uses operators like $set to modify fields.

Why this answer

The update_one method with the $set operator allows updating specific fields.

131
MCQmedium

What is the significance of the SO_BROADCAST option in a UDP socket?

A.It enables the socket to send packets to a broadcast address.
B.It allows the socket to handle incoming multicast traffic.
C.It allows the socket to listen to all ports on a machine.
D.It makes the socket connection-oriented.
AnswerA

By default, systems disallow broadcasting for safety; this option unlocks it.

Why this answer

SO_BROADCAST is a prerequisite for sending packets to the broadcast address on a network interface.

132
MCQhard

You are profiling your code and identify that a specific method is called millions of times. You decide to use a descriptor to optimize attribute access. What must the descriptor implement to intercept attribute assignment?

A.The __call__ method
B.The __init__ method
C.Only the __get__ method
D.The __set__ method
AnswerD

__set__ allows the descriptor to intercept and handle assignment.

Why this answer

A data descriptor is defined as an object that implements both __get__ and __set__ (or __delete__).

133
MCQhard

In a PyMongo application, what happens when you use 'insert_many' with 'ordered=False'?

A.The driver ignores all errors.
B.Documents are inserted in parallel.
C.The driver attempts to insert all documents regardless of individual failures.
D.The operation stops at the first error.
AnswerC

Unordered inserts continue processing even if one document fails.

Why this answer

If 'ordered' is False, the driver continues to insert subsequent documents even if one fails.

134
MCQmedium

You are using Pool.apply_async(). How do you retrieve the result of the function call?

A.Wait for the function to return.
B.Use the join() method on the pool.
C.Pass a callback function.
D.Call the get() method on the returned object.
E.Check the pool's result list.
AnswerD

Get() retrieves the result of the asynchronous task.

Why this answer

The apply_async method returns an AsyncResult object, and you must call the get() method on it.

135
MCQmedium

When implementing the Strategy pattern, what is the best way to inject the strategy into the context object?

A.Pass the strategy instance to the context's constructor
B.Use a global variable for the strategy
C.Import the strategy module inside the context's run method
D.Hardcode the strategy class inside the context's __init__ method
AnswerA

Constructor injection is a standard way to provide the required strategy implementation.

Why this answer

Dependency injection, usually via the constructor, allows the context to remain agnostic of the specific strategy implementation.

136
MCQmedium

Why should you use a 'with' statement when using a Lock?

A.It allows multiple threads to acquire the lock.
B.It automatically handles lock acquisition and release.
C.It increases the performance of the lock.
D.It creates a thread-safe environment.
E.It prevents the lock from being garbage collected.
AnswerB

It ensures the lock is released reliably.

Why this answer

It automatically acquires and releases the lock, ensuring it is released even if an exception occurs.

137
MCQmedium

You are implementing a Prototype pattern. What is the difference between shallow copy and deep copy in the context of cloning objects?

A.Shallow copy duplicates the reference, deep copy duplicates the object contents
B.Both copies result in the same memory address
C.Shallow copy clones nested objects, deep copy does not
D.Deep copy is always faster than shallow copy
AnswerA

This accurately describes the distinction in Python's copy module.

Why this answer

A shallow copy creates a new object but references the same nested objects, while a deep copy recursively clones all nested objects.

138
MCQhard

You are managing subprocesses using subprocess.Popen. Which attribute of the Popen object should you check to verify the exit code after the process terminates?

A.returncode
B.code
C.status
D.poll()
E.exit_code
AnswerA

Returncode holds the exit status of the process.

Why this answer

The returncode attribute is populated after the process finishes or wait() is called.

139
Multi-Selectmedium

Which TWO of the following are valid ways to execute a raw SQL query in SQLAlchemy?

Select 2 answers
A.Using engine.execute('SELECT * FROM table')
B.Using session.query(RawSQL('SELECT * FROM table'))
C.Using session.execute(text('SELECT * FROM table'))
D.Using session.commit('SELECT * FROM table')
E.Using table.run('SELECT * FROM table')
AnswersA, C

Engine execute is a common way for raw SQL execution.

Why this answer

SQLAlchemy allows executing raw SQL via text() with engine.execute() or session.execute().

140
MCQeasy

In a Python TCP server, what is the primary purpose of the backlog parameter in the listen(backlog) method?

A.It sets the timeout for idle client sockets.
B.It limits the total number of connected clients.
C.It specifies the maximum number of bytes per packet.
D.It defines the maximum length of the queue of pending connections.
AnswerD

The backlog value represents the number of unaccepted connections the system will queue.

Why this answer

The backlog defines the maximum number of queued connections allowed before the OS starts rejecting new ones.

141
MCQmedium

When connecting to a MongoDB instance using PyMongo, what is the role of the 'MongoClient' object?

A.It serves as the main connection handle to the MongoDB cluster.
B.It stores individual documents in memory.
C.It defines the schema for BSON documents.
D.It translates SQL queries into MQL.
AnswerA

MongoClient manages the connection pool and authentication.

Why this answer

The MongoClient acts as the entry point to the MongoDB server, allowing access to databases and collections.

142
MCQhard

When configuring a connection pool in SQLAlchemy, what does the 'pool_size' parameter define?

A.The number of retries before failure.
B.The timeout duration for queries.
C.Number of persistent connections kept in the pool.
D.Maximum number of simultaneous sessions.
AnswerC

pool_size controls the connection pool capacity.

Why this answer

pool_size defines the number of persistent connections to keep open in the pool.

143
MCQeasy

What command-line flag is used in pytest to stop the test suite execution after the first failure?

A.--stop
B.-x
C.-f
D.--halt
AnswerB

-x is the correct flag for exiting on the first failure.

Why this answer

The -x (or --exitfirst) flag causes pytest to exit immediately upon the first failed test.

144
MCQmedium

In SQLAlchemy, what is the difference between 'lazy='select'' and 'lazy='joined'' loading strategies?

A.joined loading causes N+1 query problems.
B.select loading executes a separate SQL statement when the attribute is first accessed.
C.joined loading is always faster.
D.select loading is the default for all relationships.
AnswerB

Lazy loading (select) emits a new query on access.

Why this answer

joined loading performs an outer join to fetch related objects in the same query, whereas select loading fetches them only when accessed.

145
MCQeasy

When optimizing Python code, which tool should you use to identify hot spots in the execution path?

A.pydoc
B.pdb
C.unittest
D.cProfile
AnswerD

cProfile provides deterministic profiling of Python programs.

Why this answer

cProfile is the standard built-in profiler in Python for identifying performance bottlenecks.

146
MCQhard

You are using the Composite pattern to represent a tree structure of UI elements. What is the most critical challenge when implementing a 'get_parent' method in this pattern?

A.It requires the Leaf objects to also implement the same parent reference logic
B.It makes the children too independent
C.It requires the base Component class to store a reference to the parent
D.Python's memory management cannot handle circular references
AnswerC

To support get_parent, the child needs a reference to its container, which adds maintenance overhead.

Why this answer

The Composite pattern typically flows downward; maintaining an upward reference (parent pointer) creates bidirectional dependencies that make removing or moving nodes complex.

147
MCQmedium

Which 'unittest' assertion is best suited to verify that two floating-point numbers are equal within a certain tolerance?

A.assertAlmostEqual
B.assertGreater
C.assertEqual
D.assertSequenceEqual
AnswerA

This supports a 'places' or 'delta' argument for tolerance.

Why this answer

assertAlmostEqual is specifically designed to handle floating-point precision issues by comparing values within a specified delta.

148
MCQmedium

How do you check how many times a mock object was called?

A.mock.called_times
B.len(mock.calls)
C.mock.call_count
D.mock.get_call_count()
AnswerC

This is the correct property for counting calls.

Why this answer

The 'call_count' attribute on a MagicMock or Mock object keeps track of the number of times it has been called.

149
MCQmedium

You are developing an application using SQLAlchemy and need to retrieve a single object by its primary key. Which method is preferred for this operation?

A.Model.find(pk)
B.session.get(Model, pk)
C.session.fetch(Model, pk)
D.session.query(Model).filter(Model.id == pk).first()
AnswerB

session.get() is designed specifically for primary key lookups.

Why this answer

The get() method on the Session object is the optimized way to retrieve an object by its primary key.

150
Multi-Selecteasy

Which TWO of the following are Python object-oriented concepts?

Select 2 answers
A.Global functions
B.Pointers
C.Polymorphism
D.Inheritance
E.Header files
AnswersC, D

Polymorphism allows objects to be treated as instances of their parent class.

Why this answer

Inheritance and Polymorphism are fundamental OOP pillars in Python.

Page 1

Page 2 of 3

Page 3

All pages