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.
Python Advanced MCQs
1 min read
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
Correct Answer: b) weakref
Explanation:
The weakref module allows programmers to create references to objects without increasing their reference count, permitting memory cleanup.
Correct Answer: b) id()
Explanation:
In CPython, id(object) returns the integer representing the memory address where the object is stored.
Correct Answer: b) queue.Queue
Explanation:
queue.Queue provides a thread-safe multi-producer, multi-consumer FIFO queue implementation using locks internally.
Correct Answer: b) **str**
Explanation:
**str** returns an informal, nicely printable string representation of an object, whereas **repr** aims to be unambiguous.
Correct Answer: b) **repr**
Explanation:
If **str** is missing, Python falls back to **repr** to generate a string representation.
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.
Correct Answer: a) gc.collect()
Explanation:
gc.collect() forces a full or generation-specific collection run to recycle unreferenced objects and detect cyclic references.
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.
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.
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.
Correct Answer: b) dis
Explanation:
The dis module supports disassembling CPython bytecode into readable representations for analysis.
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.
Correct Answer: b) **delete**
Explanation:
In descriptor protocol, **delete**(self, instance) is called when an attribute is explicitly deleted from an instance.
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.
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.
Correct Answer: b) **enter** and **exit**
Explanation:
Context managers implement **enter**() to initialize context and **exit**() to handle teardown and exceptions.
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.
Correct Answer: b) ast
Explanation:
The ast module helps Python applications process trees of Python abstract syntax grammar for analysis or modification.
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.
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.
Correct Answer: b) types.MappingProxyType
Explanation:
types.MappingProxyType accepts a mapping and creates a read-only proxy view of the underlying dictionary.
Correct Answer: b) LOAD_GLOBAL
Explanation:
LOAD_GLOBAL retrieves global variables or built-ins from the current execution frame's globals/builtins dict.
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.
Correct Answer: a) @functools.singledispatch
Explanation:
@functools.singledispatch enables dynamic function overloading based on the type of the first argument.
Correct Answer: b) itertools
Explanation:
The itertools module provides fast, memory-efficient building blocks for iterator manipulation written in optimized C.
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.
Correct Answer: b) (self, exc_type, exc_val, exc_tb)
Explanation:
**exit** must accept four arguments: self, exception type, exception value, and traceback object.
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.
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.
Correct Answer: a) ThreadPoolExecutor
Explanation:
ThreadPoolExecutor manages threads, which are suited for I/O-bound operations because GIL is released during I/O blockages.
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.
Correct Answer: a) tracemalloc.start()
Explanation:
tracemalloc.start() begins tracing Python memory allocations to pinpoint memory usage and memory leaks.
Correct Answer: b) Assignment Expressions (Walrus Operator `:=`)
Explanation:
PEP 572 introduced assignment expressions via the := operator, enabling value assignment inside expressions.
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.
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.
Correct Answer: a) generator.close()
Explanation:
generator.close() raises GeneratorExit at the point where the generator function was suspended to permit cleanup.
Correct Answer: b) *
Explanation:
In match/case statements, the underscore (*) acts as a wildcard pattern matching any subject without variable binding.
Correct Answer: a) abc
Explanation:
The abc module defines ABCMeta and @abstractmethod to enforce class interface contracts.
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.
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.
Correct Answer: b) os
Explanation:
The os module provides a direct interface to OS-dependent functionality including process creation and file descriptors.
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.
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.
Correct Answer: b) By invoking super().**getattribute**(name)
Explanation:
Calling self.**dict** inside **getattribute** causes infinite recursion. Accessing super().**getattribute**(name) circumvents this loop.
Correct Answer: b) array
Explanation:
The array module defines object types for compact storage of basic values like integers or floating-point numbers.
Correct Answer: a) struct.unpack()
Explanation:
struct.unpack(format, buffer) parses C binary byte layouts back into corresponding Python tuples.
Correct Answer: b) pickle
Explanation:
The pickle module serializes and deserializes complex Python object structures into binary streams.
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.
Correct Answer: a) **reduce**
Explanation:
**reduce** returns either a string or a tuple describing how to reconstruct the object during deserialization.
Correct Answer: b) ExceptionGroup
Explanation:
Python 3.11 introduced ExceptionGroup along with except* syntax to handle multiple exceptions occurring concurrently.
Correct Answer: b) except* Exception:
Explanation:
The except* operator selectively handles specific exceptions within an ExceptionGroup while allowing remaining ones to propagate.
Correct Answer: a) multiprocessing.shared_memory
Explanation:
multiprocessing.shared_memory enables direct shared memory access across distinct Python processes without serialization overhead.
Correct Answer: a) Py_INCREF()
Explanation:
In the CPython C API, Py_INCREF(op) increments the reference count for object op.
Correct Answer: b) **del**
Explanation:
**del** is the destructor method called when an instance's reference count reaches zero.
Correct Answer: b) contextvars
Explanation:
The contextvars module manages context-local state across concurrent asynchronous coroutines and event loops.
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.
Correct Answer: a) flush=True
Explanation:
Passing flush=True forces the print function to instantly flush the output stream buffer.
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.
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.
Correct Answer: b) eval()
Explanation:
eval() evaluates a single dynamic expression string and returns the computed result.
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.
Correct Answer: a) compile()
Explanation:
compile(source, filename, mode) parses string source code into a code object suitable for execution.
Correct Answer: b) inspect.getsource()
Explanation:
inspect.getsource(object) reads and returns the source code of a live Python object as a string.
Correct Answer: b) defaultdict
Explanation:
defaultdict overrides **missing**(key) to automatically populate missing entries using a specified factory.
Correct Answer: a) ChainMap
Explanation:
ChainMap groups multiple dictionaries or mappings together to create a single, updateable search view.
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.
Correct Answer: a) heapq
Explanation:
heapq provides min-heap algorithm functions on standard Python lists.
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.
Correct Answer: a) bisect.bisect_left()
Explanation:
bisect_left locates the insertion point for a value in a sorted sequence to keep it sorted.
Correct Answer: b) To customize subclass creation without writing a full metaclass
Explanation:
**init_subclass** allows base classes to hook into subclass creation directly.
Correct Answer: a) **doc**
Explanation:
**doc** stores string documentation declared at the top of functions, classes, or modules.
Correct Answer: a) @property
Explanation:
@property wraps getter execution so a class method can be accessed like a plain instance attribute.
Correct Answer: a) @price.setter
Explanation:
Applying @price.setter to a method binds it as the assignment handler for the `price` property.
Correct Answer: a) **len**
Explanation:
**len** defines the custom logic executed when len(obj) is evaluated.
Correct Answer: a) **getitem**
Explanation:
**getitem**(self, key) handles index or key retrieval using square bracket syntax.
Correct Answer: a) **setitem**
Explanation:
**setitem**(self, key, value) handles assignment via square brackets.
Correct Answer: a) **iter** and **next**
Explanation:
Iterators must implement **iter**() returning self, and **next**() returning subsequent items.
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.
Correct Answer: a) operator.itemgetter()
Explanation:
operator.itemgetter(item) constructs a callable that fetches an item from its operand.
Correct Answer: a) operator.attrgetter()
Explanation:
operator.attrgetter(attr) creates a fast callable that extracts specified attributes.
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.
Correct Answer: a) func.cache_clear()
Explanation:
cache_clear() clears all stored entries in the LRU cache attached to the function.
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.
Correct Answer: a) @typing.override
Explanation:
@typing.override explicitly indicates to static type checkers that a method is intended to override a superclass method.
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.
Correct Answer: a) sys.getrefcount()
Explanation:
sys.getrefcount(obj) returns the current reference count of the object (including temporary reference from getrefcount argument).
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.
Correct Answer: a) subprocess
Explanation:
The subprocess module lets you spawn processes, connect to input/output/error pipes, and obtain return codes.
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.
Correct Answer: a) **call**
Explanation:
Implementing **call** allows instance objects to be invoked like standard functions.
Correct Answer: a) Frame object (`frame`)
Explanation:
Frame objects represent state details during code execution, holding local variables, globals, and bytecode execution pointers.
Related Posts

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,…
October 19, 2026By MCQs Generator

Java Functions MCQs
In Java, functions are formally known as methods and serve as modular blocks of reusable code encapsulated within classes. A…
October 19, 2026By MCQs Generator

Python Arrays MCQs
Unlike many other programming languages, Python does not have a built-in static array data structure in its core syntax, instead…
August 27, 2026By MCQs Generator
Related Categories

AI & Data Science MCQ
5 topics
By MCQs Generator

Arts & Humanities MCQ
4 topics
By MCQs Generator

Civil Engineering MCQ
4 topics
By MCQs Generator

Commerce & Business MCQ
4 topics
By MCQs Generator

Competitive Exams MCQ
5 topics
By MCQs Generator

Electrical & Electronics Engineering MCQ
3 topics
By MCQs Generator

General Knowledge MCQ
2 topics
By MCQs Generator

General Science MCQ
4 topics
By MCQs Generator

Law & Judiciary MCQ
3 topics
By MCQs Generator

Mechanical Engineering MCQ
4 topics
By MCQs Generator

Medical & Health Sciences MCQ
4 topics
By MCQs Generator

Modern Tech Fields MCQ
3 topics
By MCQs Generator