Python Advanced MCQs

1 min read

Advanced Python programming moves beyond basic syntax and data structures into the fundamental mechanics of how CPython executes code under the hood. Key advanced concepts include metaprogramming with custom metaclasses, class creation pipelines via new and init, closure mechanics, custom context managers, and descriptor protocols (__get__, __set__). Furthermore, understanding high-throughput architecture requires deep insight into the Global Interpreter Lock (GIL), asynchronous event loops with asyncio, generator delegation via yield from, and reference-counting garbage collection. Mastering these advanced features enables software engineers to write memory-efficient, concurrent, and highly extensible framework level code.

1. Which module in Python's standard library provides low-level, high-performance interface bindings for atomic C-style memory buffers across distinct memory layouts?

a) ctypes
b) mmap
c) memoryview
d) struct
Correct Answer: c) memoryview
Explanation:
The memoryview object allows Python code to access the internal data of an object that supports the buffer protocol without copying, enabling high-performance memory operations.

2. In Python metaclasses, which special method is called to instantiate the class object itself before `__init__` is invoked?

a) **call**
b) **new**
c) **prepare**
d) **init_subclass**
Correct Answer: b) **new**
Explanation:
The metaclass **new** method is responsible for creating and returning the new class object, whereas **init** initializes the already created class object.

3. What is the primary role of the `__prepare__` method when implemented inside a metaclass?

a) To initialize instance variables
b) To set up the class attribute dictionary (namespace) prior to class body execution
c) To compile Python bytecode into native assembly
d) To manage asynchronous coroutines within class execution
Correct Answer: b) To set up the class attribute dictionary (namespace) prior to class body execution
Explanation:
**prepare** is called before the class body is evaluated and must return a mapping (dictionary-like object) used as the local namespace during class definition.

4. Which descriptor method distinguishes a 'data descriptor' from a 'non-data descriptor' in Python?

a) **get**
b) **set**
c) **call**
d) **name**
Correct Answer: b) **set**
Explanation:
If an object defines **set** or **delete**, it is considered a data descriptor. If it defines only **get**, it is a non-data descriptor.

5. What is the lookup precedence order when accessing an attribute `obj.x` on an instance `obj` of class `Cls`?

a) Instance dict -> Data descriptor -> Non-data descriptor -> Class dict
b) Data descriptor -> Instance dict -> Non-data descriptor -> Class dict
c) Class dict -> Non-data descriptor -> Instance dict -> Data descriptor
d) Data descriptor -> Class dict -> Instance dict -> Non-data descriptor
Correct Answer: b) Data descriptor -> Instance dict -> Non-data descriptor -> Class dict
Explanation:
Python checks for a data descriptor in the class hierarchy first. If found, its **get** is called. Otherwise, it checks instance **dict**, then non-data descriptors, and finally class attributes.

6. What exception is raised when `next()` is called on an exhausted generator that does not handle termination?

a) GeneratorExit
b) StopIteration
c) RuntimeError
d) KeyError
Correct Answer: b) StopIteration
Explanation:
When a generator function finishes executing or executes a return statement, it raises a StopIteration exception to signal the end of iteration.

7. Starting in Python 3.7, what happens if an unhandled `StopIteration` exception is explicitly raised inside a generator function?

a) It silently terminates the loop
b) It is converted into a RuntimeError
c) It resets the generator iterator
d) It causes a Segmentation Fault
Correct Answer: b) It is converted into a RuntimeError
Explanation:
Per PEP 479, raising StopIteration explicitly inside a generator is transformed into a RuntimeError to prevent silent iteration bugs.

8. Which method in the `asyncio` module is used to run a coroutine as the main entry point and manage the event loop lifecycle?

a) asyncio.start()
b) asyncio.run()
c) asyncio.execute()
d) asyncio.get_event_loop().go()
Correct Answer: b) asyncio.run()
Explanation:
asyncio.run() creates a new event loop, runs the passed coroutine until completion, closes the loop, and cleans up resources.

9. What decorator from `functools` provides automatic memoization by caching function return values based on call arguments?

a) @functools.cache
b) @functools.memoize
c) @functools.store
d) @functools.remember
Correct Answer: a) @functools.cache
Explanation:
Introduced in Python 3.9, @functools.cache is a lightweight, unbounded caching decorator equivalent to lru_cache(maxsize=None).

10. Which function in `sys` allows developers to set a custom frame-level tracing callback for debuggers and coverage tools?

a) sys.settrace()
b) sys.setdebug()
c) sys.setprofile()
d) sys.setframe()
Correct Answer: a) sys.settrace()
Explanation:
sys.settrace() sets the system trace function, which is called whenever a code frame is entered, exited, or a line is executed.

11. In Python 3, what algorithm is strictly used to construct the Method Resolution Order (MRO)?

a) Depth-First Search
b) Breadth-First Search
c) C3 Linearization
d) Dijkstra's Algorithm
Correct Answer: c) C3 Linearization
Explanation:
Python uses C3 Linearization to determine the order in which base classes are searched when resolving methods in complex inheritance hierarchies.

12. Which module in Python's standard library provides weak references that do not prevent referenced objects from being garbage collected?

a) gc
b) weakref
c) types
d) ctypes
Correct Answer: b) weakref
Explanation:
The weakref module allows programmers to create references to objects without increasing their reference count, permitting memory cleanup.

13. What built-in function returns the memory address of an object in CPython?

a) hex()
b) id()
c) hash()
d) address()
Correct Answer: b) id()
Explanation:
In CPython, id(object) returns the integer representing the memory address where the object is stored.

14. Which of the following creates a thread-safe FIFO queue in Python for inter-thread communication?

a) collections.deque
b) queue.Queue
c) asyncio.Queue
d) multiprocessing.Array
Correct Answer: b) queue.Queue
Explanation:
queue.Queue provides a thread-safe multi-producer, multi-consumer FIFO queue implementation using locks internally.

15. Which magic method controls the string representation returned by `str(obj)` intended to be human-readable?

a) **repr**
b) **str**
c) **format**
d) **unicode**
Correct Answer: b) **str**
Explanation:
**str** returns an informal, nicely printable string representation of an object, whereas **repr** aims to be unambiguous.

16. If `__str__` is not implemented in a class, what fallback magic method does Python call when `str(obj)` is executed?

a) **unicode**
b) **repr**
c) **format**
d) **name**
Correct Answer: b) **repr**
Explanation:
If **str** is missing, Python falls back to **repr** to generate a string representation.

17. Which CPython mechanism guarantees that only one native thread executes Python bytecode at any given moment?

a) Global Interpreter Lock (GIL)
b) Atomic Code Engine
c) Thread Executable Mutex
d) Virtual Bytecode Switcher
Correct Answer: a) Global Interpreter Lock (GIL)
Explanation:
The GIL is a global mutex in CPython that prevents multiple native threads from executing Python bytecodes simultaneously.

18. What function in the `gc` module forces an immediate generation-based garbage collection sweep?

a) gc.collect()
b) gc.sweep()
c) gc.clean()
d) gc.purge()
Correct Answer: a) gc.collect()
Explanation:
gc.collect() forces a full or generation-specific collection run to recycle unreferenced objects and detect cyclic references.

19. What is the effect of setting `__slots__` inside a Python class definition?

a) It disables method execution
b) It suppresses the creation of an instance `__dict__`, reducing memory usage
c) It forces all attributes to become private automatically
d) It turns the class into a Singleton
Correct Answer: b) It suppresses the creation of an instance `__dict__`, reducing memory usage
Explanation:
**slots** allocates a static array of attribute references instead of a dynamic **dict**, lowering memory consumption per instance.

20. Which keyword is used in Python generators to delegate iteration entirely to a sub-generator or iterable?

a) yield from
b) yield delegate
c) yield sub
d) yield over
Correct Answer: a) yield from
Explanation:
yield from creates a transparent channel between the caller and a sub-iterator, delegating value emission and exception handling.

21. What parameter is automatically passed to the `__init_subclass__` class method when a parent class is inherited?

a) The instance of the subclass
b) The newly created subclass object itself
c) The class dict of the parent
d) A tuple of base classes
Correct Answer: b) The newly created subclass object itself
Explanation:
**init_subclass** is executed whenever the containing class is subclassed, receiving the new subclass as its first argument.

22. Which standard library module allows direct manipulation and inspection of Python bytecode instructions?

a) inspect
b) dis
c) ast
d) codeop
Correct Answer: b) dis
Explanation:
The dis module supports disassembling CPython bytecode into readable representations for analysis.

23. What object type does an `async def` function return when called directly without using `await` or `asyncio.run()`?

a) A promise
b) A coroutine object
c) A future object
d) None
Correct Answer: b) A coroutine object
Explanation:
Calling an async function creates and returns a coroutine object without executing the function body until awaited or scheduled.

24. Which descriptor method is invoked when `del obj.attr` is executed on a class with descriptor properties?

a) **del**
b) **delete**
c) **delattr**
d) **remove**
Correct Answer: b) **delete**
Explanation:
In descriptor protocol, **delete**(self, instance) is called when an attribute is explicitly deleted from an instance.

25. What is the principal purpose of the `__class_getitem__` class method added in Python 3.7?

a) To allow indexing on instances
b) To enable generic type hinting on class objects like `MyClass[T]`
c) To intercept metaclass instantiation
d) To iterate through subclass fields
Correct Answer: b) To enable generic type hinting on class objects like `MyClass[T]`
Explanation:
**class_getitem** allows classes to support square-bracket indexing directly on class objects for parameterized type hinting.

26. Which function in `dataclasses` allows defining dynamic or complex default values using factory functions?

a) dataclass.factory()
b) field(default_factory=...)
c) dataclass.field_default()
d) field(factory_mode=True)
Correct Answer: b) field(default_factory=...)
Explanation:
field(default_factory=...) provides a callable to generate default values for mutable types like lists or dicts in dataclasses.

27. What special method allows an instance of a user-defined class to behave like a context manager in a `with` statement?

a) **start** and **stop**
b) **enter** and **exit**
c) **open** and **close**
d) **init** and **del**
Correct Answer: b) **enter** and **exit**
Explanation:
Context managers implement **enter**() to initialize context and **exit**() to handle teardown and exceptions.

28. When an exception occurs inside a `with` block, how can the `__exit__` method suppress the exception from propagating?

a) By returning a truthy value (e.g., True)
b) By raising StopIteration
c) By returning False
d) By setting exception.suppress = True
Correct Answer: a) By returning a truthy value (e.g., True)
Explanation:
If **exit** returns True (or a truthy value), Python suppresses the caught exception; if it returns False or None, the exception propagates.

29. Which module provides structural abstract syntax tree (AST) generation and compilation in Python?

a) compiler
b) ast
c) code
d) parser
Correct Answer: b) ast
Explanation:
The ast module helps Python applications process trees of Python abstract syntax grammar for analysis or modification.

30. What happens when a function decorated with `@classmethod` is called?

a) It receives the instance `self` as the first argument
b) It receives the class object `cls` as the first argument
c) It receives no implicit first argument
d) It operates strictly on static variables
Correct Answer: b) It receives the class object `cls` as the first argument
Explanation:
@classmethod binds the function to the class, passing the class object as the first positional parameter implicitly.

31. What parameter is passed as the first implicit argument to a `@staticmethod`?

a) self
b) cls
c) No implicit argument is passed
d) module
Correct Answer: c) No implicit argument is passed
Explanation:
@staticmethod defines a regular function bound to a class namespace; it receives no automatic self or cls arguments.

32. Which of the following creates an immutable dictionary view in Python's standard library `types` module?

a) types.ImmutableDict
b) types.MappingProxyType
c) types.ReadOnlyDict
d) types.DictView
Correct Answer: b) types.MappingProxyType
Explanation:
types.MappingProxyType accepts a mapping and creates a read-only proxy view of the underlying dictionary.

33. Which bytecode instruction is executed by CPython to load a global variable into the execution frame?

a) LOAD_FAST
b) LOAD_GLOBAL
c) LOAD_NAME
d) LOAD_ATTR
Correct Answer: b) LOAD_GLOBAL
Explanation:
LOAD_GLOBAL retrieves global variables or built-ins from the current execution frame's globals/builtins dict.

34. Which bytecode instruction is used by CPython for local variable access inside functions for maximum speed?

a) LOAD_GLOBAL
b) LOAD_FAST
c) LOAD_NAME
d) LOAD_DEREF
Correct Answer: b) LOAD_FAST
Explanation:
LOAD_FAST accesses local variables directly from an array indexed by integer offsets, making local variable lookups faster than dict lookups.

35. What function in the `functools` module transforms a single-dispatch generic function into different implementations based on the type of its first argument?

a) @functools.singledispatch
b) @functools.overload
c) @functools.dispatch
d) @functools.type_dispatch
Correct Answer: a) @functools.singledispatch
Explanation:
@functools.singledispatch enables dynamic function overloading based on the type of the first argument.

36. Which module in Python's standard library provides high-performance lock-free atomic iterators like `count`, `cycle`, and `repeat`?

a) collections
b) itertools
c) functools
d) operator
Correct Answer: b) itertools
Explanation:
The itertools module provides fast, memory-efficient building blocks for iterator manipulation written in optimized C.

37. What is the effect of using `asyncio.gather()` versus `asyncio.wait()`?

a) gather returns results directly in order; wait returns completed and pending sets of tasks
b) gather accepts only threads; wait accepts coroutines
c) wait is non-blocking while gather blocks the GIL
d) gather cancels failed tasks automatically while wait ignores errors
Correct Answer: a) gather returns results directly in order; wait returns completed and pending sets of tasks
Explanation:
asyncio.gather returns an ordered aggregate list of results, whereas asyncio.wait provides done and pending task sets.

38. In Python context managers, what parameter list signature must `__exit__` implement?

a) (self)
b) (self, exc_type, exc_val, exc_tb)
c) (self, exception)
d) (self, status_code)
Correct Answer: b) (self, exc_type, exc_val, exc_tb)
Explanation:
**exit** must accept four arguments: self, exception type, exception value, and traceback object.

39. What does `sys.intern()` do when applied to a string in Python?

a) Encrypts the string in memory
b) Stores only a single copy of the string in an internal dictionary to optimize memory and fast pointer comparison
c) Converts string characters into ASCII integers
d) Compiles the string into executable bytecode
Correct Answer: b) Stores only a single copy of the string in an internal dictionary to optimize memory and fast pointer comparison
Explanation:
sys.intern() ensures that identical interned strings share the exact same memory address, enabling fast identity checks using pointer comparison.

40. Which tool in the `concurrent.futures` package is best suited for CPU-bound tasks in Python?

a) ThreadPoolExecutor
b) ProcessPoolExecutor
c) AsyncIOExecutor
d) EventLoopExecutor
Correct Answer: b) ProcessPoolExecutor
Explanation:
ProcessPoolExecutor uses side-by-side operating system processes to bypass the CPython Global Interpreter Lock (GIL) for CPU-bound computation.

41. Which tool in `concurrent.futures` is ideal for I/O-bound tasks involving blocking network requests?

a) ThreadPoolExecutor
b) ProcessPoolExecutor
c) JITExecutor
d) SubprocessExecutor
Correct Answer: a) ThreadPoolExecutor
Explanation:
ThreadPoolExecutor manages threads, which are suited for I/O-bound operations because GIL is released during I/O blockages.

42. What is the purpose of `typing.overload` in Python static typing?

a) To allow multiple functions with different implementation bodies in the same scope
b) To specify multiple function signatures for a single implementation body for type checkers
c) To increase runtime execution speed of polymorphic functions
d) To override base class methods without warning
Correct Answer: b) To specify multiple function signatures for a single implementation body for type checkers
Explanation:
@typing.overload lets developers define type annotations for functions that accept different combinations of argument types.

43. Which function in the `tracemalloc` module starts tracing memory allocation blocks in Python?

a) tracemalloc.start()
b) tracemalloc.begin()
c) tracemalloc.trace_on()
d) tracemalloc.enable()
Correct Answer: a) tracemalloc.start()
Explanation:
tracemalloc.start() begins tracing Python memory allocations to pinpoint memory usage and memory leaks.

44. What is the primary feature introduced by PEP 572 in Python 3.8?

a) Structural Pattern Matching
b) Assignment Expressions (Walrus Operator `:=`)
c) Position-only parameters
d) Asynchronous comprehensions
Correct Answer: b) Assignment Expressions (Walrus Operator `:=`)
Explanation:
PEP 572 introduced assignment expressions via the := operator, enabling value assignment inside expressions.

45. Which method in a Python generator is used to send a value back into the generator execution context at a `yield` statement?

a) generator.send()
b) generator.push()
c) generator.inject()
d) generator.next(val)
Correct Answer: a) generator.send()
Explanation:
generator.send(value) resumes execution and sends a value into the generator function, which becomes the result of the current yield expression.

46. What exception is raised inside a generator when calling `generator.throw()`?

a) The exception class or instance passed as an argument to throw()
b) GeneratorExit
c) StopIteration
d) RuntimeError
Correct Answer: a) The exception class or instance passed as an argument to throw()
Explanation:
generator.throw(exc) raises the provided exception type at the point where the generator was suspended.

47. What method is invoked automatically on a generator object when it is garbage collected while still active?

a) generator.close()
b) generator.stop()
c) generator.clear()
d) generator.destroy()
Correct Answer: a) generator.close()
Explanation:
generator.close() raises GeneratorExit at the point where the generator function was suspended to permit cleanup.

48. In structural pattern matching (Python 3.10+), which wildcard character matches any single pattern without binding a variable name?

a) *
b) _
c) ?
d) ...
Correct Answer: b) *
Explanation:
In match/case statements, the underscore (*) acts as a wildcard pattern matching any subject without variable binding.

49. Which module allows user-defined classes to create custom ABCs (Abstract Base Classes) enforcing abstract methods?

a) abc
b) typing
c) types
d) base
Correct Answer: a) abc
Explanation:
The abc module defines ABCMeta and @abstractmethod to enforce class interface contracts.

50. What happens if a concrete subclass fails to override an `@abstractmethod` inherited from an ABC?

a) A syntax error occurs during file compilation
b) Instantiation of the subclass raises a TypeError
c) The class compiles and executes normally until the method is invoked
d) A Warning is logged at runtime
Correct Answer: b) Instantiation of the subclass raises a TypeError
Explanation:
Python prevents direct instantiation of subclasses that have not implemented all inherited abstract methods.

51. In Python, what does the expression `type(name, bases, dict)` accomplish when called with three arguments?

a) Checks if name exists in bases dict
b) Dynamically creates and returns a new class object
c) Returns the class type hierarchy as a tuple
d) Creates a namedtuple instance
Correct Answer: b) Dynamically creates and returns a new class object
Explanation:
Calling type() with three arguments dynamically constructs a class object with given name, base tuple, and namespace dictionary.

52. What module in standard library provides low-level OS interface functionality such as `fork()`, `exec()`, and pipe management?

a) sys
b) os
c) platform
d) shutil
Correct Answer: b) os
Explanation:
The os module provides a direct interface to OS-dependent functionality including process creation and file descriptors.

53. Which decorator from `functools` preserves original function metadata (like name and docstring) inside custom wrappers?

a) @functools.wraps
b) @functools.update_wrapper
c) @functools.copy_meta
d) @functools.preserve
Correct Answer: a) @functools.wraps
Explanation:
@functools.wraps is applied to wrapper functions inside decorators to copy function attributes (**name**, **doc**) from the wrapped function.

54. What is the primary difference between `__getattr__` and `__getattribute__`?

a) **getattr** is called for every access; **getattribute** is only called when attribute is missing
b) **getattribute** is called unconditionally for every attribute access; **getattr** is called only when lookup fails
c) **getattr** handles methods; **getattribute** handles properties
d) **getattribute** is deprecated in Python 3
Correct Answer: b) **getattribute** is called unconditionally for every attribute access; **getattr** is called only when lookup fails
Explanation:
**getattribute** is always invoked first for attribute access, whereas **getattr** acts as a fallback when the attribute is not found.

55. To prevent infinite recursion inside `__getattribute__`, how must attribute lookups be safely executed?

a) By using self.**dict**[name]
b) By invoking super().**getattribute**(name)
c) By invoking getattr(self, name)
d) By accessing object.**dict** directly
Correct Answer: b) By invoking super().**getattribute**(name)
Explanation:
Calling self.**dict** inside **getattribute** causes infinite recursion. Accessing super().**getattribute**(name) circumvents this loop.

56. Which standard library module provides memory-efficient, mutably sized arrays constrained to C-style primitive data types?

a) ctypes
b) array
c) struct
d) bytearray
Correct Answer: b) array
Explanation:
The array module defines object types for compact storage of basic values like integers or floating-point numbers.

57. What function converts binary byte structures into Python tuples according to a format string layout?

a) struct.unpack()
b) ctypes.cast()
c) codecs.decode()
d) marshal.loads()
Correct Answer: a) struct.unpack()
Explanation:
struct.unpack(format, buffer) parses C binary byte layouts back into corresponding Python tuples.

58. Which module allows serialization of arbitrary Python object trees into binary byte streams specifically for Python-to-Python storage?

a) json
b) pickle
c) yaml
d) marshal
Correct Answer: b) pickle
Explanation:
The pickle module serializes and deserializes complex Python object structures into binary streams.

59. Why is unpickling untrusted binary streams considered dangerous in Python?

a) It causes immediate GIL deadlock
b) It can execute arbitrary code during object deserialization via `__reduce__`
c) It modifies global variable definitions permanent in CPython memory
d) It corrupts the trace logger
Correct Answer: b) It can execute arbitrary code during object deserialization via `__reduce__`
Explanation:
Pickle deserialization allows the object constructor to invoke arbitrary commands or functions, creating severe security vulnerabilities.

60. Which method in the `pickle` protocol can be defined on a custom class to customize its serialization and executable reconstruction?

a) **reduce**
b) **serialize**
c) **pack**
d) **encode**
Correct Answer: a) **reduce**
Explanation:
**reduce** returns either a string or a tuple describing how to reconstruct the object during deserialization.

61. In Python 3.11+, which exception group type allows handling multiple concurrent exceptions raised in TaskGroups?

a) MultiException
b) ExceptionGroup
c) AggregateError
d) TaskErrorGroup
Correct Answer: b) ExceptionGroup
Explanation:
Python 3.11 introduced ExceptionGroup along with except* syntax to handle multiple exceptions occurring concurrently.

62. Which syntax construct introduced in Python 3.11 is used to catch individual exception types from an `ExceptionGroup`?

a) except Group(Exception):
b) except* Exception:
c) try_group Exception:
d) catch Exception:
Correct Answer: b) except* Exception:
Explanation:
The except* operator selectively handles specific exceptions within an ExceptionGroup while allowing remaining ones to propagate.

63. What module in Python provides zero-copy inter-process shared memory buffers?

a) multiprocessing.shared_memory
b) sys.shared
c) threading.shared_bytes
d) queue.SharedBuffer
Correct Answer: a) multiprocessing.shared_memory
Explanation:
multiprocessing.shared_memory enables direct shared memory access across distinct Python processes without serialization overhead.

64. What is the CPython reference count increment function in C API?

a) Py_INCREF()
b) Py_ADDREF()
c) Py_NEWREF()
d) Py_PLUSREF()
Correct Answer: a) Py_INCREF()
Explanation:
In the CPython C API, Py_INCREF(op) increments the reference count for object op.

65. Which method is called on an object when it is about to be garbage-collected in Python?

a) **destroy**
b) **del**
c) **finalize**
d) **dispose**
Correct Answer: b) **del**
Explanation:
**del** is the destructor method called when an instance's reference count reaches zero.

66. In Python context-local storage for asynchronous tasks, which module provides isolated context variable support?

a) threading.local
b) contextvars
c) asyncio.local
d) sys.context
Correct Answer: b) contextvars
Explanation:
The contextvars module manages context-local state across concurrent asynchronous coroutines and event loops.

67. What does `asyncio.TaskGroup` provide in Python 3.11+?

a) A thread pool manager
b) An asynchronous context manager for reliable task cleanup and structured concurrency
c) A low-level system call wrapper
d) A process monitoring tool
Correct Answer: b) An asynchronous context manager for reliable task cleanup and structured concurrency
Explanation:
asyncio.TaskGroup provides structured concurrency, holding child tasks safely and handling error propagation reliably.

68. What parameter allows `print()` to immediately flush its output buffer to standard output?

a) flush=True
b) now=True
c) buffer=False
d) sync=True
Correct Answer: a) flush=True
Explanation:
Passing flush=True forces the print function to instantly flush the output stream buffer.

69. In static typing (`typing`), what does `TypeVar` enable?

a) Variable runtime assignment validation
b) Generic type parameters for functions and classes
c) Automatic casting of strings to integers
d) Dynamic variable name resolution
Correct Answer: b) Generic type parameters for functions and classes
Explanation:
TypeVar is used to declare generic type variables for type hints across classes and functions.

70. What is the purpose of `typing.ParamSpec` introduced in Python 3.10?

a) To define parameter requirements for command line execution
b) To forward callable parameter signatures across higher-order functions and decorators
c) To convert dicts into dynamic keyword argument objects
d) To validate parameter bounds in math functions
Correct Answer: b) To forward callable parameter signatures across higher-order functions and decorators
Explanation:
ParamSpec captures signature details of a callable argument to enable precise decorator typing.

71. Which built-in function dynamically evaluates string-form Python expressions and returns the computed result?

a) exec()
b) eval()
c) compile()
d) parse()
Correct Answer: b) eval()
Explanation:
eval() evaluates a single dynamic expression string and returns the computed result.

72. What is the difference between `eval()` and `exec()`?

a) eval evaluates a single expression returning a value; exec executes multi-line code statements returning None
b) exec is faster than eval
c) eval accepts C code; exec accepts Python code
d) eval is thread-safe; exec is not thread-safe
Correct Answer: a) eval evaluates a single expression returning a value; exec executes multi-line code statements returning None
Explanation:
eval() parses single expressions and returns results, whereas exec() parses and executes statements dynamically.

73. What function compiles a string into a code object that can be passed into `exec()` or `eval()`?

a) compile()
b) build()
c) assemble()
d) tokenize()
Correct Answer: a) compile()
Explanation:
compile(source, filename, mode) parses string source code into a code object suitable for execution.

74. In the `inspect` module, which function retrieves the raw source code of a module, class, or method as a string?

a) inspect.getcode()
b) inspect.getsource()
c) inspect.fetchsource()
d) inspect.read_file()
Correct Answer: b) inspect.getsource()
Explanation:
inspect.getsource(object) reads and returns the source code of a live Python object as a string.

75. Which class in `collections` provides a dictionary subclass that calls a factory function to supply missing values?

a) OrderedDict
b) defaultdict
c) ChainMap
d) UserDict
Correct Answer: b) defaultdict
Explanation:
defaultdict overrides **missing**(key) to automatically populate missing entries using a specified factory.

76. What data structure from `collections` allows efficiently grouping multiple mappings into a single context view?

a) ChainMap
b) CombinedDict
c) MultiDict
d) MergedMapping
Correct Answer: a) ChainMap
Explanation:
ChainMap groups multiple dictionaries or mappings together to create a single, updateable search view.

77. Which algorithm does `collections.deque` use to guarantee O(1) appends and pops from both ends?

a) Dynamic Array Resizing
b) Doubly Linked List of fixed-size blocks
c) Binary Search Tree
d) Hash Table with open addressing
Correct Answer: b) Doubly Linked List of fixed-size blocks
Explanation:
deque is implemented as a doubly linked list of fixed-length blocks, ensuring O(1) operations on both ends.

78. What module in standard library provides a heap queue algorithm implementation (priority queue)?

a) heapq
b) priorityqueue
c) queue
d) trees
Correct Answer: a) heapq
Explanation:
heapq provides min-heap algorithm functions on standard Python lists.

79. In `heapq`, what does `heapq.heappushpop(heap, item)` do?

a) Pushes item on the heap, then pops and returns the smallest item from the heap
b) Pops smallest item first, then pushes new item
c) Pushes item twice
d) Pops all elements from the heap
Correct Answer: a) Pushes item on the heap, then pops and returns the smallest item from the heap
Explanation:
heappushpop pushes the new item and pops the smallest element in a single efficient step.

80. Which function in `bisect` module finds the position where an element should be inserted into a sorted list to maintain sorted order?

a) bisect.bisect_left()
b) bisect.find()
c) bisect.insert_point()
d) bisect.search_index()
Correct Answer: a) bisect.bisect_left()
Explanation:
bisect_left locates the insertion point for a value in a sorted sequence to keep it sorted.

81. What is the purpose of the `__init_subclass__` method in Python?

a) To initialize instance variables of subclasses
b) To customize subclass creation without writing a full metaclass
c) To register subclasses into global memory
d) To override parent **init** methods automatically
Correct Answer: b) To customize subclass creation without writing a full metaclass
Explanation:
**init_subclass** allows base classes to hook into subclass creation directly.

82. Which special attribute contains the docstring defined at the beginning of a class, function, or module?

a) **doc**
b) **documentation**
c) **info**
d) **help**
Correct Answer: a) **doc**
Explanation:
**doc** stores string documentation declared at the top of functions, classes, or modules.

83. Which standard decorator turns a class method into a read-only property attribute?

a) @property
b) @attribute
c) @getter
d) @field
Correct Answer: a) @property
Explanation:
@property wraps getter execution so a class method can be accessed like a plain instance attribute.

84. How do you define a setter for a property named `price` in a Python class?

a) @price.setter
b) @property.set(price)
c) @set_price
d) @setter(price)
Correct Answer: a) @price.setter
Explanation:
Applying @price.setter to a method binds it as the assignment handler for the `price` property.

85. What magic method implements container length determination for `len(obj)`?

a) **len**
b) **size**
c) **count**
d) **length**
Correct Answer: a) **len**
Explanation:
**len** defines the custom logic executed when len(obj) is evaluated.

86. Which method enables subscript access on custom container objects via `obj[key]`?

a) **getitem**
b) **getindex**
c) **lookup**
d) **subscript**
Correct Answer: a) **getitem**
Explanation:
**getitem**(self, key) handles index or key retrieval using square bracket syntax.

87. Which magic method enables assignment to subscripted indexes via `obj[key] = value`?

a) **setitem**
b) **putitem**
c) **assign**
d) **setindex**
Correct Answer: a) **setitem**
Explanation:
**setitem**(self, key, value) handles assignment via square brackets.

88. What method must an iterator object implement to satisfy Python's iterator protocol?

a) **iter** and **next**
b) **get_next**
c) **yield**
d) **loop**
Correct Answer: a) **iter** and **next**
Explanation:
Iterators must implement **iter**() returning self, and **next**() returning subsequent items.

89. What is the main advantage of generators over lists for large data processing?

a) Generators evaluate lazily, consuming memory only for one item at a time
b) Generators run in parallel automatically
c) Generators can be indexed directly
d) Generators bypass the GIL
Correct Answer: a) Generators evaluate lazily, consuming memory only for one item at a time
Explanation:
Generators compute items on demand rather than allocating memory for all items in advance.

90. Which function in the `operator` module performs item access operations equivalent to `lambda x: x[item]`?

a) operator.itemgetter()
b) operator.attrgetter()
c) operator.methodcaller()
d) operator.get_element()
Correct Answer: a) operator.itemgetter()
Explanation:
operator.itemgetter(item) constructs a callable that fetches an item from its operand.

91. Which function in `operator` extracts attributes equivalent to `lambda x: getattr(x, attr)`?

a) operator.attrgetter()
b) operator.itemgetter()
c) operator.propertygetter()
d) operator.field()
Correct Answer: a) operator.attrgetter()
Explanation:
operator.attrgetter(attr) creates a fast callable that extracts specified attributes.

92. What does `@functools.lru_cache(maxsize=128)` do?

a) Caches the last 128 results of a function based on arguments using an LRU eviction policy
b) Limits function calls to 128 execution runs
c) Allocates 128 MB of memory to function evaluation
d) Throttles API requests
Correct Answer: a) Caches the last 128 results of a function based on arguments using an LRU eviction policy
Explanation:
@functools.lru_cache memoizes return values up to maxsize items using a Least Recently Used eviction algorithm.

93. Which method on an `@lru_cache` wrapped function clears its cached entries?

a) func.cache_clear()
b) func.clear()
c) func.reset_cache()
d) func.purge()
Correct Answer: a) func.cache_clear()
Explanation:
cache_clear() clears all stored entries in the LRU cache attached to the function.

94. What is the purpose of `typing.Final` introduced in Python 3.8?

a) Declares that a variable, method, or class cannot be reassigned, overridden, or subclassed
b) Forces garbage collection at the end of function execution
c) Closes dynamic modules
d) Converts objects to immutable tuples
Correct Answer: a) Declares that a variable, method, or class cannot be reassigned, overridden, or subclassed
Explanation:
typing.Final indicates to static type checkers that an attribute cannot be mutated or overridden.

95. Which decorator in `typing` marks a method as overriding a base class method in Python 3.12+?

a) @typing.override
b) @typing.implements
c) @typing.super
d) @typing.extend
Correct Answer: a) @typing.override
Explanation:
@typing.override explicitly indicates to static type checkers that a method is intended to override a superclass method.

96. What does `typing.TypedDict` provide in Python?

a) A runtime type-checked class
b) Type annotations for dictionary keys and specific value types for static type checking
c) A C-accelerated dictionary
d) An immutable hash map
Correct Answer: b) Type annotations for dictionary keys and specific value types for static type checking
Explanation:
TypedDict allows annotating dictionaries where specific string keys map to designated value types.

97. Which function in `sys` returns the current refcount of an object?

a) sys.getrefcount()
b) sys.refcount()
c) sys.count_references()
d) sys.inspect_ref()
Correct Answer: a) sys.getrefcount()
Explanation:
sys.getrefcount(obj) returns the current reference count of the object (including temporary reference from getrefcount argument).

98. What is the primary function of `sys.setrecursionlimit()`?

a) To change the maximum depth of the Python call stack
b) To limit memory allocated to recursive functions
c) To limit iteration loops
d) To set max thread allocations
Correct Answer: a) To change the maximum depth of the Python call stack
Explanation:
sys.setrecursionlimit(limit) adjusts the maximum depth limit of the Python interpreter stack.

99. Which module in Python allows executing dynamic subprocesses and capturing standard I/O pipes?

a) subprocess
b) os.process
c) sys.child
d) shell
Correct Answer: a) subprocess
Explanation:
The subprocess module lets you spawn processes, connect to input/output/error pipes, and obtain return codes.

100. What parameter in `subprocess.run()` automatically raises a `CalledProcessError` if the executed subprocess exits with a non-zero code?

a) check=True
b) raise_error=True
c) strict=True
d) assert_success=True
Correct Answer: a) check=True
Explanation:
Setting check=True inside subprocess.run causes it to raise CalledProcessError if the process exits with an error code.

101. What magic method is called when an object is called as a function via `obj()`?

a) **call**
b) **invoke**
c) **run**
d) **execute**
Correct Answer: a) **call**
Explanation:
Implementing **call** allows instance objects to be invoked like standard functions.

102. In CPython internals, what object represents an isolated execution frame on the call stack?

a) Frame object (`frame`)
b) Trace object
c) Stack instance
d) Execution context
Correct Answer: a) Frame object (`frame`)
Explanation:
Frame objects represent state details during code execution, holding local variables, globals, and bytecode execution pointers.
← Previous: Latest Python Operators MCQs
Next →: Python Arrays MCQs
Java Control Flow / If Else MCQs

Java Control Flow / If Else MCQs

Control flow statements in Java determine the exact order in which code instructions and expressions execute during runtime. By default,…

By MCQs Generator
Java Functions MCQs

Java Functions MCQs

In Java, functions are formally known as methods and serve as modular blocks of reusable code encapsulated within classes. A…

By MCQs Generator
Python Arrays MCQs

Python Arrays MCQs

Unlike many other programming languages, Python does not have a built-in static array data structure in its core syntax, instead…

By MCQs Generator