Courseiva

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

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

Page 1 of 3

Page 2
1
MCQeasy

You are using sqlite3 in Python and need to ensure that data integrity is maintained when performing multiple related INSERT operations. Which method should you call on the connection object to commit your changes?

A.connection.save()
B.connection.flush()
C.cursor.apply()
D.connection.commit()
AnswerD

commit() is the standard method to finalize a transaction in sqlite3.

Why this answer

The commit() method is used to save the current transaction to the database.

2
MCQmedium

You are configuring a server to handle high-concurrency requests. Why is it preferable to use the select.select() module over a simple blocking recv() loop?

A.It reduces the CPU usage of the Python interpreter during idle times.
B.It automatically implements multi-threaded socket handling.
C.It automatically handles TCP flow control packets.
D.It enables monitoring multiple socket descriptors for I/O readiness.
AnswerD

select permits waiting for multiple sockets without blocking the thread.

Why this answer

select.select() allows monitoring multiple sockets simultaneously, preventing the server from blocking on a single idle connection.

3
MCQeasy

What is the primary benefit of the Facade pattern when working with legacy libraries?

A.It increases the performance of the underlying legacy library
B.It automatically patches security vulnerabilities in legacy code
C.It allows you to rewrite the legacy code
D.It provides a simplified, unified interface to a complex subsystem
AnswerD

This is the definition of the Facade pattern.

Why this answer

A Facade simplifies complex library interactions by providing a cleaner, more intuitive interface for the client.

4
MCQeasy

Which Python library is the standard built-in interface for SQLite databases?

A.pymongo
B.sqlite3
C.sqlalchemy
D.db-api
AnswerB

sqlite3 is the standard library module.

Why this answer

The 'sqlite3' module is part of the Python standard library.

5
MCQhard

In a multi-threaded Python server, why is it discouraged to share a single socket object across multiple threads without synchronization?

A.Python's GIL prevents concurrent socket access.
B.Concurrent access can lead to interleaved or corrupted data streams.
C.Sockets are not picklable.
D.The socket module raises a RuntimeError for concurrent usage.
AnswerB

Shared descriptors without locking can cause race conditions in the application logic.

Why this answer

Socket operations are generally thread-safe in CPython, but overlapping operations on the same file descriptor can lead to interleaved data or corrupted state.

6
Multi-Selectmedium

Which TWO of the following are true regarding the socket.shutdown() method?

Select 2 answers
A.It can be used to disable only the receiving side of the socket.
B.It is identical to the close() method.
C.It causes an immediate memory deallocation of the socket object.
D.It can be used to disable only the sending side of the socket.
E.It automatically reopens the socket if called twice.
AnswersA, D

SHUT_RD stops the input stream.

Why this answer

shutdown() can disable reading, writing, or both, which is useful for protocol-level signaling.

7
MCQhard

You are utilizing abstract base classes (ABCs). How do you enforce that a subclass implements a specific method?

A.Use a metaclass check
B.Use the @abstractmethod decorator
C.Raise NotImplementedError in the base class
D.Pass the method name to __init__
AnswerB

@abstractmethod ensures the subclass cannot be instantiated without overriding the method.

Why this answer

The @abstractmethod decorator marks a method as requiring implementation in concrete subclasses.

8
MCQhard

You need to prevent an object's attribute from being modified after it is set. Which approach provides the most robust implementation?

A.Using a class attribute instead of instance attribute
B.Using a @property decorator with no setter
C.Overriding __setattr__ to disallow modification
D.Setting the attribute to private using double underscores
AnswerB

A @property without a @name.setter makes the attribute read-only.

Why this answer

A property with only a getter (or a custom setter that raises an exception) effectively creates a read-only attribute.

9
MCQmedium

You have an object that behaves like a function. Which magic method must be implemented to make this possible?

A.__call__
B.__apply__
C.__invoke__
D.__function__
AnswerA

__call__ turns an object into a callable.

Why this answer

The __call__ method allows an object instance to be invoked as a function.

10
MCQmedium

When implementing the Command pattern in Python, what is a primary advantage of using a 'Command' class hierarchy?

A.It eliminates the need for functions
B.It allows commands to be queued, logged, or undone by the invoker
C.It automatically makes all operations thread-safe
D.It forces the application to use a specific GUI framework
AnswerB

Encapsulation as an object allows for these operations.

Why this answer

It allows commands to be treated as objects, which enables features like queuing, logging, and undo/redo.

11
MCQmedium

In the Decorator pattern, why is it preferred to use the functools.wraps decorator when creating a function decorator?

A.It automatically implements the Singleton pattern
B.It prevents the decorator from being applied multiple times
C.It preserves the metadata of the original function
D.It ensures the function runs faster
AnswerC

This is exactly what functools.wraps is designed for.

Why this answer

functools.wraps preserves the metadata (like __name__ and __doc__) of the original function, which is critical for debugging and reflection.

12
MCQeasy

Which of the following is the correct way to close a socket object in Python?

A.socket.destroy()
B.socket.shutdown()
C.socket.close()
D.del socket
AnswerC

close() is the standard way to release the socket resource.

Why this answer

The close() method should be called on the socket object to release the underlying file descriptor.

13
MCQeasy

When using the 'unittest' framework, which method is executed exactly once before any test methods in a class are run?

A.setUp
B.pre_test
C.init
D.setUpClass
AnswerD

This is the correct class method to run setup code once for the entire class.

Why this answer

The 'setUpClass' method is a class method that runs once before all tests in the class, whereas 'setUp' runs before each individual test.

14
MCQhard

What is the primary purpose of the subprocess.PIPE constant?

A.To terminate the child process.
B.To speed up subprocess execution.
C.To create a channel for data transfer.
D.To close the standard input.
E.To redirect output to a file.
AnswerC

PIPE enables interaction with the process streams.

Why this answer

It is used to indicate that a new pipe to the child process should be created for stdout or stdin.

15
MCQeasy

Which method should a developer use to retrieve the IP address and port of the remote peer connected to a TCP socket?

A.socket.recvfrom()
B.socket.getpeername()
C.socket.getsockname()
D.socket.getfqdn()
AnswerB

getpeername() is the correct method for remote connection details.

Why this answer

getpeername() returns the address of the remote endpoint connected to the socket.

16
MCQmedium

How do you retrieve the number of documents matched by a PyMongo 'find' operation without fetching all documents into memory?

A.cursor.count()
B.collection.size()
C.len(list(cursor))
D.collection.count_documents(filter)
AnswerD

count_documents is the modern, non-deprecated method.

Why this answer

The count_documents() method on a collection is the recommended way to get a count.

17
MCQeasy

Which module allows you to run external programs and interact with their input/output streams?

A.sys
B.subprocess
C.multiprocessing
D.os
E.threading
AnswerB

Subprocess is the standard for managing processes.

Why this answer

The subprocess module is the recommended way to spawn new processes and connect to their pipes.

18
Multi-Selecteasy

Which THREE of the following are common benefits of using a mocking framework in testing?

Select 3 answers
A.Isolating the code from external dependencies.
B.Automatically rewriting broken business logic.
C.Reducing execution time for I/O operations.
D.Deploying the application to production.
E.Simulating complex error conditions.
AnswersA, C, E

Core benefit of unit testing.

Why this answer

Mocking isolates the unit under test, speeds up tests by replacing I/O, and enables testing of error paths that are hard to trigger.

19
MCQhard

In 'unittest.mock', when you want to return a specific value based on the input arguments of a mocked function, which property should be configured?

A.call_args
B.return_value
C.side_effect
D.configure_mock
AnswerC

Assigning a function to side_effect allows dynamic response based on arguments.

Why this answer

The 'side_effect' property allows you to assign a function that computes the return value dynamically based on arguments, unlike 'return_value' which is static.

20
Multi-Selectmedium

Which THREE of the following are common characteristics of the Observer pattern?

Select 3 answers
A.Observers are forced to be synchronous
B.Automatic notification when the subject's state changes
C.A one-to-many relationship between objects
D.The subject is tightly coupled to the concrete observers
E.Loose coupling between the subject and the observers
AnswersB, C, E

This is the primary behavior of the pattern.

Why this answer

One-to-many relationship, event notification, and loose coupling are key.

21
MCQeasy

Which of the following is a classic use case for the Builder pattern in Python?

A.Adding new behaviors to an object at runtime
B.Constructing complex objects step-by-step with various configurations
C.Creating a simple object with no parameters
D.Ensuring only one instance of a class exists
AnswerB

This is the primary purpose of the Builder pattern.

Why this answer

The Builder pattern is ideal when an object requires many steps to construct or has many optional configuration parameters, avoiding 'telescoping constructors'.

22
MCQmedium

You are using a multiprocessing.Semaphore(3). What happens when the 4th process attempts to acquire the semaphore?

A.It blocks until a slot is released.
B.It creates a new process slot.
C.It raises an exception.
D.It bypasses the lock.
E.It is terminated by the OS.
AnswerA

This is the standard behavior for a semaphore.

Why this answer

The 4th process will block until one of the previous three processes releases the semaphore.

23
Multi-Selecthard

Which THREE of the following are valid scopes for a pytest fixture?

Select 3 answers
A.method
B.function
C.session
D.class
E.test
AnswersB, C, D

Default scope.

Why this answer

The valid scopes in pytest are function, class, module, package, and session.

24
Multi-Selecteasy

Which TWO of the following are necessary to connect a TCP client to a server?

Select 2 answers
A.socket.listen()
B.socket.bind()
C.socket.socket()
D.socket.connect()
E.socket.accept()
AnswersC, D

Required to create the socket object.

Why this answer

The client must have an instantiated socket and call connect() with the correct target address tuple.

25
Multi-Selecthard

Which TWO of the following are true regarding 'unittest' test suites?

Select 2 answers
A.Test classes must inherit from unittest.TestCase.
B.All test methods must start with the word 'test'.
C.Fixtures must be named 'setUp' and 'tearDown'.
D.You cannot run unittest from the command line.
E.Test suites are limited to 10 tests each.
AnswersA, B

Inheritance is required for the framework to pick up the tests.

Why this answer

Suites can be built using TestLoader, and tests are aggregated from classes inheriting from unittest.TestCase.

26
MCQeasy

You are writing a Python script that needs to perform heavy I/O-bound tasks concurrently. Which module should you prioritize to minimize the overhead of global interpreter lock (GIL) contention?

A.queue
B.threading
C.subprocess
D.asyncio
E.multiprocessing
AnswerB

Threading is efficient for I/O-bound tasks because it allows concurrent waiting.

Why this answer

The threading module is ideal for I/O-bound tasks as it releases the GIL during blocking operations, whereas multiprocessing is better for CPU-bound tasks.

27
MCQhard

Which pytest feature allows you to run the same test multiple times with different sets of inputs?

A.@pytest.mark.repeat
B.pytest.loop()
C.@pytest.mark.parametrize
D.@pytest.fixture(params=...)
AnswerC

This is the built-in way to run tests with multiple inputs.

Why this answer

Parametrization using @pytest.mark.parametrize allows a test function to be executed with varying data sets.

28
MCQeasy

If you want to run a function in a background thread, which class should you instantiate?

A.threading.Thread
B.threading.Process
C.subprocess.Thread
D.multiprocessing.Thread
E.thread.Task
AnswerA

The Thread class is for spawning threads.

Why this answer

The threading.Thread class is the standard way to create threads.

29
Multi-Selecthard

Which THREE of the following options can be used with socket.setsockopt()?

Select 3 answers
A.socket.TCP_BUFFER_SIZE
B.socket.SO_KEEPALIVE
C.socket.SO_REUSEADDR
D.socket.TCP_NODELAY
E.socket.SO_MAX_CONNECTIONS
AnswersB, C, D

Enables keep-alive packets.

Why this answer

SO_REUSEADDR, SO_KEEPALIVE, and TCP_NODELAY are standard options supported by most systems.

30
MCQeasy

You need to ensure that a class can only be instantiated once throughout the application lifecycle. Which design pattern is most appropriate?

A.Factory Pattern
B.Adapter Pattern
C.Proxy Pattern
D.Singleton Pattern
AnswerD

Singleton restricts instantiation to a single object.

Why this answer

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

31
MCQeasy

When managing resources like file handles, what is the best practice to ensure they are always closed?

A.Using a context manager (with statement)
B.Manually calling .close()
C.Relying on garbage collection
D.Using a try-finally block
AnswerA

The with statement guarantees resource release.

Why this answer

The with statement (context manager) ensures that cleanup code is executed regardless of exceptions.

32
Multi-Selecteasy

Which TWO of the following are structural patterns?

Select 2 answers
A.Facade
B.Command
C.Observer
D.Builder
E.Adapter
AnswersA, E

Facade is a structural pattern.

Why this answer

Adapter and Facade are classic structural patterns.

33
MCQeasy

What is the effect of setting a socket to non-blocking mode using socket.setblocking(False)?

A.It makes the socket perform asynchronous DNS lookups.
B.It increases the throughput of the connection.
C.It automatically closes the socket if it is idle.
D.It raises an exception if an operation would block.
AnswerD

Operations that cannot complete immediately throw a BlockingIOError.

Why this answer

Non-blocking sockets cause operations like recv() and connect() to raise an exception if they cannot be completed immediately.

34
MCQeasy

Which of the following best describes the benefit of using parameterized queries in sqlite3?

A.They allow for multiple database connections.
B.They improve query execution speed by pre-compiling.
C.They prevent SQL injection attacks.
D.They automatically format the output as JSON.
AnswerC

Parameterized queries ensure input is treated as data, not code.

Why this answer

Parameterized queries prevent SQL injection by separating the query logic from the data.

35
MCQhard

When implementing the Bridge pattern, what is the primary structural requirement to effectively decouple an abstraction from its implementation?

A.The implementation must use a Singleton to manage its state
B.Both the abstraction and the implementation must inherit from the same class
C.The implementation must be a subclass of the abstraction
D.The abstraction must contain an instance of the implementation interface
AnswerD

This composition allows the implementation to be swapped at runtime.

Why this answer

The abstraction must contain a reference (bridge) to an object of an implementor interface, allowing the implementation to vary independently.

36
MCQeasy

Which object would you use to share a simple integer between processes that is safe for concurrent access?

A.list
B.threading.Lock
C.multiprocessing.Value
D.global variable
E.multiprocessing.Queue
AnswerC

Value provides shared memory access to a variable.

Why this answer

multiprocessing.Value is designed specifically to share single values between processes with a lock.

37
Multi-Selecthard

Which THREE features are provided by 'pytest' but NOT by the standard 'unittest' framework?

Select 3 answers
A.Parametrization using markers.
B.Dependency injection via fixtures.
C.Support for setup and teardown methods.
D.Running tests without needing to inherit from a base class.
E.Basic assertion support.
AnswersA, B, D

pytest has this built-in.

Why this answer

pytest offers native parametrization, powerful fixture injection, and automatic test discovery without boilerplate classes.

38
Multi-Selecthard

Which THREE of the following are true regarding the use of the socket module in Python?

Select 3 answers
A.Sockets are identified by file descriptors in the OS.
B.Non-blocking sockets raise BlockingIOError if an operation cannot complete.
C.The socket.socket() function is a factory for socket objects.
D.The send() method is guaranteed to send the entire buffer requested.
E.Closing a socket does not terminate the underlying file descriptor.
AnswersA, B, C

Sockets are file-like objects backed by OS descriptors.

Why this answer

Sockets are file descriptors, they can be set to non-blocking mode, and they must be closed to avoid resource leaks.

39
MCQmedium

When using inheritance, how can you explicitly call a method from a specific parent class that is not the immediate superclass?

A.self.method()
B.BaseClass.method(self)
C.Using the __parent__ attribute
D.super().method()
AnswerB

Direct invocation on the class bypasses the MRO.

Why this answer

Calling the method directly on the class object (e.g., Parent.method(self)) bypasses the MRO.

40
MCQhard

You are applying the Facade pattern to simplify a complex subsystem consisting of three interacting legacy modules. What is the primary architectural requirement for the Facade class to be effective?

A.The Facade must inherit from every class in the subsystem
B.The Facade must implement the Singleton pattern to ensure only one interface exists
C.The Facade should expose all methods of the subsystem classes for flexibility
D.The Facade should provide a simplified interface that delegates requests to appropriate subsystem objects
AnswerD

Delegation is the key mechanism of the Facade pattern to hide complexity.

Why this answer

The Facade must act as a single entry point, encapsulating the complexity of the internal modules so the client doesn't need to know about them.

41
Multi-Selecteasy

Which TWO of the following are differences between TCP and UDP?

Select 2 answers
A.UDP is connection-oriented.
B.UDP is always faster than TCP in every network condition.
C.TCP has higher overhead than UDP.
D.TCP guarantees packet delivery.
E.TCP supports multicasting natively.
AnswersC, D

Handshaking and flow control add overhead to TCP.

Why this answer

TCP is reliable and connection-oriented, whereas UDP is connectionless and unreliable.

42
MCQeasy

Which pattern is most appropriate for a scenario where you want to provide a standard interface for a suite of related or dependent objects without specifying their concrete classes?

A.Proxy
B.Abstract Factory
C.Singleton
D.Builder
AnswerB

Abstract Factory is specifically designed for families of related objects.

Why this answer

The Abstract Factory pattern provides an interface for creating families of related objects.

43
Multi-Selectmedium

Which TWO of the following scenarios are best suited for the subprocess module?

Select 2 answers
A.Sharing memory between Python threads.
B.Running an external C++ executable.
C.Managing internal thread pools.
D.Capturing the stdout of a command-line tool.
E.Parallelizing Python functions.
AnswersB, D

Executing external binaries is a primary use case.

Why this answer

Subprocess is intended for executing external binaries and interacting with their system streams.

44
MCQeasy

In sqlite3, how do you handle a database error such as a constraint violation?

A.Check the connection status after every query.
B.Check the return value of the execute() method.
C.The library crashes the program automatically.
D.Use a try-except block to catch sqlite3.Error.
AnswerD

sqlite3 raises specific exceptions for database errors.

Why this answer

You should wrap database operations in a try-except block and catch sqlite3.Error or its subclasses.

45
Multi-Selecteasy

Which TWO of the following are valid ways to run tests?

Select 2 answers
A.unittest.execute()
B.python run_tests.py
C.import pytest; pytest.run()
D.python -m unittest
E.pytest
AnswersD, E

Standard unittest module command.

Why this answer

Both 'pytest' and 'python -m unittest' are the standard command-line ways to execute Python test suites.

46
MCQhard

You need to implement a custom class that behaves like a sequence, allowing indexing and length checking. Which magic methods are required?

A.__iter__ and __next__
B.__index__ and __size__
C.__setitem__ and __delitem__
D.__getitem__ and __len__
AnswerD

These two methods allow indexing and length retrieval.

Why this answer

To be a sequence, a class needs to implement __getitem__ and __len__.

47
MCQhard

When using a multiprocessing.Queue to share data between processes, what happens if the queue is full and you use the put() method without a timeout?

A.It restarts the child process.
B.It blocks indefinitely until a slot becomes available.
C.It raises a Full exception immediately.
D.It silently drops the data.
E.It overwrites the oldest item in the queue.
AnswerB

Default behavior of put() is to block if the queue is full.

Why this answer

By default, put() is a blocking operation that will wait until a slot is available if the queue is full.

48
Multi-Selectmedium

Which TWO of these are valid parameters for the MongoClient constructor?

Select 2 answers
A.table_prefix
B.host
C.use_sql
D.cache_size
E.username
AnswersB, E

The host parameter is valid.

Why this answer

MongoClient accepts host and port, or a connection string.

49
MCQmedium

Why is the socket.socket() constructor typically called with socket.AF_INET and socket.SOCK_STREAM for a standard web server?

A.To provide a reliable, connection-oriented byte stream.
B.To enable UDP broadcast.
C.To reduce latency for real-time video.
D.To support raw IP packet injection.
AnswerA

SOCK_STREAM is the identifier for the TCP protocol.

Why this answer

AF_INET defines IPv4 and SOCK_STREAM defines the TCP protocol, which are standard for HTTP.

50
MCQhard

In a multi-threaded application, you need to ensure that shared state is modified safely. Which tool is the most appropriate for this task?

A.time.sleep
B.sys.settrace
C.threading.Lock
D.gc.collect
AnswerC

Locks provide mutual exclusion to prevent race conditions.

Why this answer

The threading.Lock primitive allows only one thread to access a resource at a time.

51
MCQmedium

What is the purpose of the 'upsert=True' option in MongoDB update operations?

A.It creates a new document if no match is found.
B.It prevents duplicates.
C.It sorts the results before updating.
D.It forces an atomic update across a cluster.
AnswerA

Upsert is a combination of update and insert.

Why this answer

If no document matches the query, a new document is created with the update criteria.

52
MCQhard

When writing a metaclass, what is the 'cls' parameter in the __new__ method referring to?

A.The instance of the class
B.The class being created
C.The parent class
D.The metaclass itself
AnswerD

The first argument to __new__ in a metaclass is the metaclass type.

Why this answer

In a metaclass's __new__ method, 'cls' refers to the metaclass itself, not the class being created.

53
Multi-Selectmedium

Which TWO of the following are valid ways to assert that a mock was NOT called?

Select 2 answers
A.mock.check_called(None)
B.assert not mock.called
C.mock.called == False
D.mock.assert_not_called()
E.mock.assert_called_count(0)
AnswersD, E

Explicit method for this purpose.

Why this answer

assert_not_called and assert_called_count(0) are both valid methods to confirm a mock was not interacted with.

54
MCQhard

You have a thread waiting on a threading.Event. Which method should another thread call to wake up the waiting thread?

A.notify()
B.trigger()
C.start()
D.signal()
E.set()
AnswerE

Set() triggers the Event.

Why this answer

The set() method sets the internal flag to true, causing wait() to return.

55
Multi-Selecthard

Which THREE of the following are features of the 'threading' module in Python?

Select 3 answers
A.Shared memory between different processes
B.Semaphore objects
C.Lock synchronization primitives
D.Event objects for signaling
E.Automatic global interpreter lock removal
AnswersB, C, D

Semaphores are supported for resource counting.

Why this answer

The threading module provides Locks, Semaphores, and Events for synchronization.

56
Multi-Selectmedium

Which THREE of the following are benefits of the Factory Method pattern?

Select 3 answers
A.Adherence to the Open/Closed Principle
B.Eliminating all usage of 'if/else' blocks
C.Decoupling the client code from concrete classes
D.Centralizing object creation logic
E.Automatically making objects immutable
AnswersA, C, D

New product types can be added by creating new creators without changing existing code.

Why this answer

Decoupling, Open/Closed adherence, and centralized logic are the main benefits.

57
MCQhard

When using the multiprocessing module, why is it recommended to use a Manager object instead of a standard dictionary to share data between processes?

A.It is faster than standard dictionaries.
B.It is the only way to store strings.
C.It removes the need for locks.
D.It allows local storage of values.
E.It ensures the dictionary is synchronized between processes.
AnswerE

The manager provides a proxy that handles the necessary IPC.

Why this answer

A manager process is created to host the objects, allowing them to be shared safely between different processes using proxy objects.

58
Multi-Selectmedium

Which THREE of the following are standard ways to implement the 'Strategy' pattern in Python?

Select 3 answers
A.Injecting the strategy instance at runtime
B.Defining classes with a common interface
C.Hardcoding the strategy selection logic in the context
D.Using a global variable to change strategy behavior
E.Passing a function as an argument
AnswersA, B, E

Dependency injection is standard for the Strategy pattern.

Why this answer

Using functions, classes, or dependency injection are all valid strategies.

59
MCQeasy

Which of the following is true regarding daemon threads in Python?

A.They are only used for system-level tasks.
B.They are guaranteed to finish before the program ends.
C.They are abruptly terminated when the main process exits.
D.They use more memory than regular threads.
E.They cannot create child threads.
AnswerC

Daemon threads are force-stopped by the interpreter.

Why this answer

Daemon threads are terminated abruptly when the main program exits, which can lead to incomplete operations.

60
MCQmedium

You need to detect if a client has disconnected from your TCP server. What is the standard behavior of recv() when the peer performs a clean shutdown?

A.It raises a ConnectionResetError.
B.It returns None.
C.It blocks indefinitely.
D.It returns an empty string (b'').
AnswerD

An empty bytes object is the indicator of an orderly EOF in TCP.

Why this answer

A clean shutdown by the peer causes recv() to return an empty bytes object (b'').

61
MCQeasy

Which operator is used to perform bitwise AND operations?

A.&&
B.&
C.^
D.|
AnswerB

& performs bitwise AND.

Why this answer

The & operator is the bitwise AND operator in Python.

62
MCQhard

Which of these is the most effective way to test a function that uses 'time.sleep()' without actually waiting?

A.Use a faster machine.
B.Patch 'time.sleep'.
C.Use pytest.raises.
D.Change the sleep duration to 0.
AnswerB

Mocking the function avoids the delay entirely.

Why this answer

Mocking the 'time.sleep' function prevents it from actually executing the sleep command, making tests run faster.

63
MCQhard

Which of the following describes the behavior of TCP_NODELAY?

A.It disables Nagle's algorithm for low-latency communication.
B.It forces the socket to ignore packet loss.
C.It enables UDP-like performance for TCP.
D.It increases the packet size to match MTU.
AnswerA

This allows small packets to be sent without waiting for buffer filling.

Why this answer

TCP_NODELAY disables Nagle's algorithm, which otherwise buffers small packets to send them as one, reducing network overhead but increasing latency.

64
MCQmedium

In the Memento pattern, which component is responsible for storing the state of the Originator without exposing its internal structure?

A.The Memento
B.The Caretaker
C.The Originator's public properties
D.A global database
AnswerA

The Memento object stores the state effectively acting as a snapshot.

Why this answer

The Memento object acts as an opaque carrier of the state, ensuring the Originator's internals remain private.

65
MCQhard

You are implementing a custom type in SQLAlchemy. Which method must be overridden to convert data from the database type back to a Python object?

A.load_dialect_impl
B.process_result_value
C.bind_processor
D.process_bind_param
AnswerB

This converts DB results into Python objects.

Why this answer

The process_result_value method is responsible for type conversion during retrieval.

66
MCQmedium

Which object in SQLAlchemy is responsible for maintaining a collection of loaded objects and managing their lifecycle?

A.Engine
B.Session
C.Query
D.MetaData
AnswerB

The session tracks object states like 'persistent' and 'dirty'.

Why this answer

The Session object acts as a workspace for objects and tracks their state.

67
MCQeasy

Which function in the socket module is used to convert a 32-bit integer from host byte order to network byte order?

A.socket.ntohl()
B.socket.htons()
C.socket.htonl()
D.socket.inet_aton()
AnswerC

htonl is used for 32-bit integer conversion.

Why this answer

htonl() stands for Host to Network Long, converting 32-bit integers for network transmission.

68
MCQhard

You are using SQLAlchemy with an asynchronous driver (asyncio). Which object must be used to perform database operations asynchronously?

A.Engine.async
B.AsyncSession
C.None of the above
D.AsyncConnection
E.Session
AnswerB

AsyncSession supports awaitable methods for database access.

Why this answer

AsyncSession is the required class for asynchronous session management in SQLAlchemy.

69
Multi-Selecthard

Which THREE of these are valid relationship loading strategies in SQLAlchemy?

Select 3 answers
A.eager
B.subquery
C.joined
D.direct
E.lazy
AnswersB, C, E

Subquery loading uses a separate query with a subselect.

Why this answer

lazy, joined, and subquery are three common loading strategies.

70
MCQmedium

In SQLAlchemy, what does the 'metadata.create_all(engine)' command do?

A.It creates tables for all models bound to the metadata.
B.It connects to the database and tests the latency.
C.It drops all tables and recreates them.
D.It populates the tables with initial data.
AnswerA

This is the primary function of create_all.

Why this answer

It inspects the defined ORM models and emits CREATE TABLE statements to the database.

71
Multi-Selectmedium

Which TWO of the following are key benefits of using the multiprocessing.Pool class?

Select 2 answers
A.Higher performance for I/O tasks than threads.
B.Automatic process creation and management.
C.Guaranteed memory sharing between processes.
D.Automatic elimination of the GIL.
E.Simplified data return with map/starmap methods.
AnswersB, E

Pool manages the process lifecycle.

Why this answer

Pools simplify process management and provide convenient result retrieval mechanisms.

72
MCQeasy

When using the sqlite3 module, what is the primary purpose of using a context manager (the 'with' statement) on a connection object?

A.To automatically commit or rollback transactions.
B.To lock the database file for exclusive access.
C.To automatically close the connection upon exit.
D.To parse SQL queries for syntax errors.
AnswerA

The 'with' statement handles transaction control automatically.

Why this answer

In sqlite3, the connection context manager automatically commits or rolls back transactions.

73
Multi-Selecteasy

Which TWO are common pitfalls when working with SQLite databases in a multi-threaded environment?

Select 2 answers
A.Sharing a single connection object across threads
B.Excessive database locking (database is locked)
C.Memory leaks in the cursor object
D.SQL injection via parameterized queries
E.Incorrect SQL syntax
AnswersA, B

Standard sqlite3 connections are not thread-safe.

Why this answer

SQLite connections are not thread-safe by default, and lock contention can occur.

74
MCQmedium

You are handling large datasets and want to improve memory efficiency. Which Python feature allows you to iterate over a large sequence without loading it entirely into memory?

A.Generators
B.Deepcopy
C.Set literals
D.List comprehensions
AnswerA

Generators yield values on demand, saving memory.

Why this answer

Generators provide a lazy evaluation mechanism to yield items one at a time.

75
Multi-Selecteasy

Which THREE of the following represent types of IPC provided by the multiprocessing module?

Select 3 answers
A.Pipe
B.Queue
C.Thread
D.Global
E.Manager
AnswersA, B, E

Pipes provide a connection between two processes.

Why this answer

Multiprocessing provides Pipes, Queues, and Managers for inter-process communication.

Page 1 of 3

Page 2

All pages