Python Decorators & Generators MCQs

1 min read

Python decorators and generators are powerful advanced features that enable clean, modular, and high-performance programming. Decorators are higher-order functions that wrap other functions to dynamically modify or extend their behavior without altering their source code. Generators utilize the yield keyword to implement lazy evaluation, returning values one at a time on demand while preserving execution state. Mastering both constructs is essential for writing memory-efficient applications and clearing senior-level technical interviews.

1. What is the core underlying mechanism that powers decorators in Python?

0) First-class functions and closures
1) Multiple inheritance and polymorphism
2) Meta-programming via C++ bindings
3) Bytecode injection at runtime
Correct Answer:

2. What is a closure in Python?

0) A nested function that references variables from its enclosing outer scope even after the outer function has finished executing
1) A function that closes all open file streams automatically
2) An object that cannot be modified after creation
3) A mechanism to close background threads safely
Correct Answer:

3. Which attribute of a function object stores variables captured by a closure?

0) __closure__
1) __scope__
2) __free_vars__
3) __locals__
Correct Answer:

4. How do you write a decorator that accepts arguments itself (a parameterized decorator)?

0) By writing a decorator factory function that returns the actual decorator function
1) By passing arguments directly into the `@decorator(arg)` syntax which is evaluated immediately
2) Both A and B
3) Parameterized decorators are syntactically impossible in Python
Correct Answer:

5. What is the typical three-layer nested structure required for a parameterized decorator?

0) Outer factory function (accepts decorator args) -> Middle decorator function (accepts target function) -> Inner wrapper function (accepts function args)
1) Single function with keyword arguments
2) Two functions where the wrapper returns a generator
3) A class-based decorator with no nesting
Correct Answer:

6. How can you implement a decorator using a class instead of a function?

0) By defining a class with an `__init__` method (taking the function) and a `__call__` method (taking function arguments)
1) By inheriting from `BaseDecorator`
2) By using the `@classdecorator` keyword
3) Classes cannot be used as decorators
Correct Answer:

7. What is the main challenge when writing class-based decorators for instance methods?

0) The descriptor protocol (`__get__`) must be implemented so the class instance binds correctly to the instance (`self`) rather than the class
1) Classes cannot decorate methods, only standalone functions
2) Class decorators are much slower than function decorators
3) Instance methods cannot use closures
Correct Answer:

8. What does the built-in `@property` decorator do?

0) Allows a method to be accessed like an attribute (without parentheses)
1) Makes a method private to the class
2) Caches the return value of a method permanently
3) Transforms a method into a static method
Correct Answer:

9. Which decorator is used to define a static method in a class (a method that does not receive `self` or `cls`)?

0) @staticmethod
1) @classmethod
2) @abstractmethod
3) @property
Correct Answer:

10. Which decorator is used to define a class method in Python (a method that receives the class `cls` as its first argument)?

0) @classmethod
1) @staticmethod
2) @property
3) @bindmethod
Correct Answer:

11. What is the purpose of `@functools.lru_cache`?

0) It caches the results of function calls based on arguments (Least Recently Used caching) to optimize performance for repetitive calls
1) It limits the memory usage of recursive functions
2) It automatically logs all function execution errors
3) It converts synchronous functions into asynchronous coroutines
Correct Answer:

12. What requirement must function arguments meet to be cached using `@functools.lru_cache`?

0) All arguments must be hashable
1) All arguments must be integers
2) Arguments can be of any mutable or immutable type
3) Arguments must be keyword-only
Correct Answer:

13. What does the `@functools.singledispatch` decorator enable?

0) Generic functions and single-dispatch generic functions based on the type of the first argument
1) Single-threaded execution of concurrent tasks
2) Dispatching events to GUI components
3) Automatic type coercion of arguments to strings
Correct Answer:

14. Can multiple decorators be stacked on top of a single function?

0) Yes, e.g., `@dec1 @dec2 def func(): pass`
1) No, Python only allows a single decorator per function definition
2) Only if they are class-based decorators
3) Only if they take no arguments
Correct Answer:

15. In what order are stacked decorators executed when a function is called?

0) Bottom-up during application/wrapping time, but top-down (outermost to innermost) when the decorated function is actually executed
1) Top-down during application time and bottom-up during execution
2) Random order determined by memory allocation
3) Simultaneously in parallel threads
Correct Answer:

16. What is the equivalent of `@dec1 @dec2 def func(): pass` in explicit function calls?

0) func = dec1(dec2(func))
1) func = dec2(dec1(func))
2) func = dec1(func(dec2))
3) func = dec2(func(dec1))
Correct Answer:

17. What is a generator function characterized by?

0) The presence of the `yield` keyword anywhere in its body
1) The use of the `generate` keyword
2) Inheriting from the `Generator` class
3) Having no return statement whatsoever
Correct Answer:

18. What object is returned when you call a generator function?

0) A generator iterator object
1) A list containing all generated items
2) An integer representing the final value
3) A tuple of local variables
Correct Answer:

19. What happens to the local state of a generator function when it hits a `yield` statement?

0) Execution pauses, and its local state (variable bindings, instruction pointer) is saved frozen in memory until `next()` is called again
1) All local variables are destroyed and garbage collected
2) The function restarts from the beginning
3) The program terminates with a GeneratorPause exception
Correct Answer:

20. What is the primary difference between a `return` statement and a `yield` statement in a function?

0) `return` terminates the function completely and returns a final value, while `yield` pauses the function, emits a value, and allows resumption
1) `yield` can only be used inside classes, while `return` is for functions
2) `return` creates generators, while `yield` creates regular functions
3) There is no functional difference
Correct Answer:

21. What value does a generator expression yield element-by-element?

0) It computes and yields items lazily on demand
1) It evaluates all items immediately and stores them in a hidden array
2) It generates random numbers matching the expression pattern
3) It yields bytes read from disk
Correct Answer:

22. What syntax is used for a generator expression?

0) (expression for item in iterable)
1) [expression for item in iterable]
2) {expression for item in iterable}
3) generator{expression for item in iterable}
Correct Answer:

23. Can a generator expression be passed directly into a function like `sum()` or `max()` without outer parentheses?

0) Yes, if a generator expression is the sole argument to a function, the function call parentheses serve as the generator parentheses
1) No, generator expressions always require explicit surrounding parentheses
2) Only in Python 2
3) Only if wrapped in square brackets
Correct Answer:

24. What does the `send()` method on a generator object do?

0) Resumes the generator and sends a value into it, which becomes the return value of the `yield` expression inside the generator
1) Sends the generator output to a network socket
2) Sends an exception to terminate the generator
3) Resets the generator state to the beginning
Correct Answer:

25. What must happen before you can call `generator.send(value)` on a newly created generator for the first time?

0) You must prime the generator by calling `next(gen)` or `gen.send(None)` to advance execution to the first `yield` statement
1) Nothing, you can send values immediately
2) You must assign a value to `__send__`
3) You must iterate over it with a for loop first
Correct Answer:

26. What does the `throw(type, [value, [traceback]])` method on a generator do?

0) Raises an exception at the point where the generator was paused (inside the `yield` expression)
1) Throws the generator object away and frees memory
2) Raises a TypeError if the generator returns a value
3) Forces the generator to stop without raising exceptions
Correct Answer:

27. What does the `close()` method on a generator do?

0) Raises a `GeneratorExit` exception inside the generator at the suspension point, causing it to exit
1) Closes all open file handles managed by the generator
2) Pauses the generator permanently
3) Deletes the generator variable from scope
Correct Answer:

28. What exception is raised inside a generator when its `close()` method is invoked?

0) GeneratorExit
1) StopIteration
2) SystemExit
3) CloseGeneratorError
Correct Answer:

29. What is the purpose of the `yield from` syntax (introduced in Python 3.3)?

0) To delegate part of a generator's operations to a sub-generator or iterable, seamlessly yielding values from it
1) To import generator modules from external packages
2) To inherit generator properties from parent classes
3) To catch StopIteration exceptions automatically in loops
Correct Answer:

30. How does `yield from subgen()` handle return values from the sub-generator?

0) The expression `yield from subgen()` evaluates to the return value (`value` in `return value`) of the sub-generator when it finishes
1) It discards all return values
2) It raises a StopIteration exception containing the return value
3) It yields the return value as the final item
Correct Answer:

31. Can a generator function contain a `return` statement?

0) Yes, but it cannot return any value other than `None` (or empty `return`), which raises `StopIteration(value)`
1) No, return statements are strictly forbidden in generator functions
2) Yes, and it returns a list of all yielded items
3) Only if combined with `yield from`
Correct Answer:

32. What is an iterator in Python?

0) An object that implements the iterator protocol, consisting of the `__iter__()` and `__next__()` methods
1) Any list or dictionary
2) A function that uses the `yield` keyword
3) A loop control statement like `break` or `continue`
Correct Answer:

33. Is every generator an iterator?

0) Yes, all generators implement the iterator protocol
1) No, generators are functions, not iterators
2) Only when converted via `iter()`
3) Only when using `yield from`
Correct Answer:

34. Is every iterator a generator?

0) No, iterators can be custom classes implementing `__iter__` and `__next__` without being generator functions
1) Yes, all iterators are created using generator functions
2) Only built-in collection iterators
3) Yes, by definition
Correct Answer:

35. What does calling `iter(obj)` on an iterable object return?

0) An iterator object for that iterable
1) A copy of the iterable list
2) The first item of the iterable
3) A boolean indicating if it is iterable
Correct Answer:

36. What makes an object an iterable in Python?

0) An object that has an `__iter__()` method returning an iterator, or a `__getitem__()` method supporting integer indexing
1) An object that contains at least 10 items
2) An object that can be converted to a string
3) An object created with a generator expression
Correct Answer:

37. What happens when you iterate over an iterator to completion and then try to iterate over it a second time?

0) It is exhausted and yields nothing; you must create a new iterator
1) It automatically resets and starts over from the beginning
2) It raises a ReuseError
3) It repeats the last yielded value indefinitely
Correct Answer:

38. How can you write a decorator that logs the execution time of a function?

0) By recording `time.time()` before and after calling the wrapped function inside the wrapper
1) By using `@time.sleep`
2) By passing a timer object into the function arguments
3) By modifying the function's bytecode timestamps
Correct Answer:

39. What is a common use case for decorators in web frameworks like Flask or Django?

0) URL routing/endpoint registration (e.g., `@app.route('/')`) and access control/authentication checks (e.g., `@login_required`)
1) Compiling HTML templates into binary code
2) Managing database connection pools automatically via multithreading
3) Formatting JSON HTTP request bodies
Correct Answer:

40. Can decorators be used to enforce type checking on function arguments?

0) Yes, by inspecting argument types against type annotations during wrapper execution
1) No, type checking is restricted to static analyzers like mypy
2) Only on built-in functions
3) Only if the function is a generator
Correct Answer:

41. What is an asynchronous generator in Python (`async def` with `yield`)?

0) A generator function defined with `async def` that can use `await` expressions and yields values asynchronously
1) A generator that runs in a separate OS thread
2) A generator that yields network packets
3) A decorator for asynchronous coroutines
Correct Answer:

42. What loop syntax is used to iterate over an asynchronous generator?

0) async for ... in ...
1) for ... in await ...
2) await for ... in ...
3) async loop
Correct Answer:

43. What is an asynchronous decorator?

0) A decorator designed to wrap asynchronous coroutine functions (`async def`)
1) A decorator that executes in the background
2) A decorator that uses multiprocessing
3) A decorator that times out after 5 seconds
Correct Answer:

44. Why might a simple function decorator fail when applied to an asynchronous coroutine function?

0) Because if the wrapper is a standard `def` instead of `async def` and does not `await` the coroutine, it returns a coroutine object instead of executing it
1) Because coroutines cannot accept decorators
2) Because `functools.wraps` is incompatible with async functions
3) Because async functions run on C threads
Correct Answer:

45. What is memoization, and how can decorators implement it?

0) Caching function results for given arguments so expensive computations are not repeated; implemented via dictionaries or `functools.lru_cache`
1) Remembering variable names across multiple script executions
2) Storing generator states in permanent files
3) Logging function execution history to a database
Correct Answer:

46. What is the primary risk of using a simple dictionary-based memoization decorator on a function with unlimited unique arguments?

0) Unbounded memory consumption leading to a MemoryError (memory leak)
1) A RecursionError due to deep dictionary nesting
2) A TypeError when hashing large strings
3) Slower execution speed than unmemoized code
Correct Answer:

47. How do you write a decorator that retries a failing function a specified number of times?

0) By wrapping the function call in a `for` loop combined with a `try...except` block inside the wrapper
1) By using the `@retry` keyword in function definitions
2) By setting `function.retries = 3`
3) By converting the function into a generator
Correct Answer:

48. What is the purpose of `@functools.total_ordering`?

0) A class decorator that takes a class defining one or more rich comparison methods (like `__eq__` and `__lt__`) and supplies the rest
1) Sorts lists in alphabetical order automatically
2) Enforces strict numerical ordering on dictionaries
3) Orders decorators execution sequence
Correct Answer:

49. What is a context manager decorator (e.g., from `contextlib.contextmanager`)?

0) A generator function decorated with `@contextlib.contextmanager` that allows you to implement a context manager (`with` statement) using `yield`
1) A decorator that manages GUI window contexts
2) A decorator that closes generator iterators automatically
3) A thread synchronization lock decorator
Correct Answer:

50. In a `@contextlib.contextmanager` generator function, what happens to code placed after the `yield` statement?

0) It executes when exiting the `with` block (acting as the cleanup/`__exit__` logic)
1) It executes immediately before entering the `with` block
2) It is ignored completely
3) It runs concurrently in a separate thread
Correct Answer:

51. How are exceptions raised inside a `with` block handled when using `@contextlib.contextmanager`?

0) They are raised at the `yield` statement, meaning they can be caught using a `try...except` block around the `yield` statement
1) They are ignored and suppressed automatically
2) They crash the Python interpreter
3) They are converted to StopIteration exceptions
Correct Answer:

52. What is a generator pipeline?

0) Chaining multiple generators together where one generator consumes the output of another, processing data streams lazily stage-by-stage
1) A pipeline for compiling generator bytecode into C++
2) A multithreaded queue for async coroutines
3) A method to pipe generator output directly to standard output
Correct Answer:

53. Why are generator pipelines memory efficient for processing large data sets (like multi-gigabyte log files)?

0) Data items flow through the pipeline one item at a time without ever loading the entire dataset into memory at once
1) They compress data in RAM
2) They execute code on GPU hardware
3) They automatically delete processed records from the hard drive
Correct Answer:

54. What is an infinite generator?

0) A generator function that contains an infinite loop (e.g., `while True: yield x`) producing an endless sequence of values
1) A generator that runs forever without stopping or pausing
2) A generator that consumes infinite RAM
3) A decorator that never terminates
Correct Answer:

55. How can you safely consume a finite number of items from an infinite generator without entering an endless loop?

0) Using `itertools.islice()` or taking a slice/counter in a `for` loop with a break condition
1) By calling `generator.limit(n)`
2) By catching the InfiniteLoopError
3) It is impossible; infinite generators always crash loops
Correct Answer:

56. What does the `itertools.chain()` function do with multiple iterables/generators?

0) Treats multiple iterables as a single continuous sequence, consuming them sequentially
1) Chains generators together to run in parallel threads
2) Links function decorators together
3) Combines dictionaries into a single lookup table
Correct Answer:

57. What does `itertools.groupby()` require of its input iterable to group items correctly?

0) The input data must be sorted by the grouping key beforehand
1) The input data must be a dictionary
2) The input data must be reversed
3) The input data must contain only integers
Correct Answer:

58. What is the difference between a list comprehension and a generator expression in terms of execution?

0) List comprehensions build and return the full list in memory immediately, while generator expressions return a lazy iterator evaluated on demand
1) Generator expressions are faster for creating lists
2) List comprehensions use the `yield` keyword
3) There is no difference in memory or evaluation
Correct Answer:

59. When should you prefer a list comprehension over a generator expression?

0) When you need the result as a concrete list for indexing, multiple iterations, or when the dataset is small and fits easily in RAM
1) Always, list comprehensions are superior in every scenario
2) When processing infinite data streams
3) When writing asynchronous coroutines
Correct Answer:

60. What happens if you try to get the length (`len()`) of a generator object directly?

0) It raises a `TypeError: object of type 'generator' has no len()` because generators do not know their length in advance
1) It returns 0
2) It consumes the generator and returns the total item count
3) It returns the memory size of the generator
Correct Answer:

61. How can you count the number of items produced by a generator without storing them all in a list?

0) By passing the generator to `sum(1 for x in gen)` or `collections.deque(gen, maxlen=0)`
1) By calling `gen.count()`
2) By checking `gen.__len__()`
3) It is impossible
Correct Answer:

62. Can a generator function be called multiple times to produce independent iterator objects?

0) Yes, each call to the generator function creates a brand new, independent generator iterator instance with its own state
1) No, a generator function can only be called once in a program's lifecycle
2) Only if decorated with `@functools.lru_cache`
3) Only if passed through `iter()`
Correct Answer:

63. What is a coroutine in Python (historically built on generators before `async/def`)?

0) A generator that consumes data sent via `send()` and yields control back and forth cooperatively
1) A thread-safe function running on multiple CPU cores
2) A class-based decorator
3) An exception handler
Correct Answer:

64. What is the purpose of the `@abstractmethod` decorator from the `abc` module?

0) To declare abstract methods in Abstract Base Classes that must be implemented by any concrete subclasses
1) To make a method abstract and hidden from inspectors
2) To optimize method compilation speed
3) To create abstract generator pipelines
Correct Answer:

65. What happens if you try to instantiate a class that inherits from an ABC (`abc.ABC`) without implementing all of its `@abstractmethod`s?

0) Python raises a `TypeError` preventing instantiation
1) The missing methods raise NotImplementedError when called
2) The class is instantiated as a partial mock
3) A SyntaxError is triggered at compile time
Correct Answer:

66. Can a decorator modify the return value of the function it decorates?

0) Yes, the wrapper function can intercept the result of the decorated function, modify it, and return the modified value
1) No, decorators can only inspect arguments, never return values
2) Only if the function is a generator
3) Only if using class-based decorators
Correct Answer:

67. Can a decorator suppress exceptions raised by the decorated function?

0) Yes, by wrapping the function call in a `try...except` block inside the wrapper and choosing not to re-raise the exception
1) No, decorators are strictly forbidden from catching exceptions
2) Only if the function is decorated with `@suppress`
3) Only for SyntaxErrors
Correct Answer:

68. What is the difference between `@staticmethod` and a regular module-level function?

0) A static method belongs to a class's namespace and can be called on the class or its instances, whereas a module function belongs to the module file
1) Static methods are executed on GPU hardware
2) There is no difference whatsoever
3) Static methods are automatically asynchronous
Correct Answer:

69. What does `@classmethod` receive as its first argument when called?

0) The class itself (`cls`), rather than an instance (`self`)
1) The parent class of the module
2) An instance of the class (`self`)
3) A dictionary of all class attributes
Correct Answer:

70. What is a common use case for `@classmethod`?

0) Alternative constructors (e.g., `Class.from_json(data)`)
1) Creating private helper functions
2) Speeding up arithmetic loops
3) Defining generator pipelines
Correct Answer:

71. What is a property setter decorator?

0) A decorator named `@property_name.setter` used to define validation or logic when an attribute is assigned a value
1) A decorator that makes properties read-only
2) A function that sets global variables
3) A class constructor decorator
Correct Answer:

72. What happens if you define a `@property` on an attribute without providing a corresponding `.setter` decorator?

0) The attribute becomes read-only; attempting to assign to it raises an `AttributeError`
1) The attribute becomes write-only
2) Assignment works normally and stores the value in the instance dictionary
3) Python raises a SyntaxError at definition time
Correct Answer:

73. Can a generator function yield control back to the caller and receive values back simultaneously?

0) Yes, via the `val = yield output` expression where `yield` evaluates to the value sent via `gen.send(val)`
1) No, yield is strictly one-way (output only)
2) Only in asynchronous generators
3) Only if decorated with `@bidirectional`
Correct Answer:

74. What is the order of evaluation in `val = yield output`?

0) `output` is evaluated and yielded first; upon resumption, the value passed to `send()` is assigned to `val`
1) `val` is evaluated first, then yielded
2) Both are evaluated simultaneously
3) It causes a SyntaxError
Correct Answer:

75. What is a decorator factory?

0) A function that takes arguments and returns a decorator function
1) A factory class that manufactures new generator iterators
2) A design pattern to build classes dynamically
3) A tool for automated unit testing
Correct Answer:

76. How do you write a decorator that works both with and without parentheses (e.g., both `@my_dec` and `@my_dec()`)?

0) By checking if the first argument passed to the decorator is callable (the function) or not (decorator arguments), and returning either a wrapper or a decorator factory accordingly
1) It is impossible in Python
2) By using `@functools.flexible`
3) By defining two separate functions
Correct Answer:

77. What is the purpose of `functools.partial`?

0) To create a callable object with fixed positional and keyword arguments from a given function (partial application)
1) To split a generator into partial chunks
2) To partially decorate a function
3) To handle partial exceptions
Correct Answer:

78. How does `functools.reduce()` interact with generator expressions?

0) It applies a function of two arguments cumulatively to the items of the generator from left to right to reduce it to a single value
1) It reduces the generator memory usage by half
2) It splits the generator into multiple sub-generators
3) It converts the generator into a list
Correct Answer:

79. What is the primary benefit of lazy evaluation in generators regarding memory leaks?

0) Items are discarded from memory immediately after being yielded and consumed, preventing large memory accumulations
1) Generators have an automatic garbage collection trigger
2) Memory is encrypted during generator execution
3) It eliminates circular references
Correct Answer:

80. Can a generator function contain multiple `yield` statements?

0) Yes, a generator can have any number of `yield` statements, and execution resumes from the statement immediately following the one that just yielded
1) No, a generator can only contain a single `yield` statement
2) Only if inside a `while` loop
3) Only if combined with `yield from`
Correct Answer:

81. What happens when execution reaches the end of a generator function (or hits a `return` statement)?

0) A `StopIteration` exception is raised, signaling to loops that the iterator is exhausted
1) The generator restarts automatically from the beginning
2) The program halts execution
3) An infinite loop is triggered
Correct Answer:

82. How do `for` loops handle the `StopIteration` exception raised by generators behind the scenes?

0) They catch `StopIteration` silently and use it to terminate the loop cleanly
1) They convert it into a SyntaxError
2) They log it to `sys.stderr`
3) They restart the generator
Correct Answer:

83. What is a decorator used for access control or authentication typically expected to do?

0) Check if the current user session has permissions before executing the wrapped view/function, otherwise raise an exception or redirect
1) Encrypt the user password in memory
2) Log the user out after 10 minutes
3) Generate a random authentication token
Correct Answer:

84. What is a decorator used for input validation expected to do?

0) Inspect function arguments against expected types, ranges, or formats before calling the core function, raising `ValueError` or `TypeError` if invalid
1) Sanitize HTML strings in web forms
2) Compress incoming file payloads
3) Convert text into binary format
Correct Answer:

85. Can a decorator be applied to an entire class rather than a single function?

0) Yes, class decorators take a class object as an argument and return a modified or new class
1) No, decorators only apply to functions and methods
2) Only if the class inherits from `DecoratorBase`
3) Only in Python 2
Correct Answer:

86. What is a practical use case for a class decorator?

0) Automatically adding logging, debugging methods, or registering classes in a global plugin registry
1) Compiling class methods into C bytecode
2) Enforcing strict encapsulation of private variables
3) Managing generator pipelines
Correct Answer:

87. How do you inspect the original unwrapped function if it has been wrapped by multiple decorators?

0) By accessing `func.__wrapped__` recursively until the base function is reached
1) By calling `func.unwrap_all()`
2) By checking `sys.modules`
3) It is impossible once wrapped
Correct Answer:

88. What does `functools.wraps` automatically assign to the wrapper function?

0) It copies `__module__`, `__name__`, `__qualname__`, `__doc__`, and `__annotations__` from the wrapped function to the wrapper
1) It copies the function source code file from disk
2) It copies the function memory address
3) It assigns a unique UUID
Correct Answer:

89. What happens if you omit `@functools.wraps` in a custom decorator?

0) The decorated function loses its original name and docstring, taking on the wrapper function's name and docstring instead, which can break documentation tools and debugging
1) The function throws a SyntaxError
2) The function runs 50% slower
3) The function cannot accept arguments
Correct Answer:

90. What is a stateful decorator implemented via a class?

0) A decorator class that maintains state (like call counts or caches) across multiple function calls using instance attributes
1) A decorator that stores state in the operating system registry
2) A decorator that runs in a dedicated thread
3) A decorator that saves data to an SQLite database
Correct Answer:

91. Can a function decorator be implemented as a generator function?

0) Function decorators return callable wrapper functions, so a generator itself cannot act directly as a standard function decorator unless it wraps and returns a callable
1) Yes, any generator can decorate a function
2) Only if using `yield from`
3) Yes, by calling `next()` on the decorator
Correct Answer:

92. What is a generator expression compared to list comprehension in terms of memory footprint?

0) Generator expression has O(1) space complexity regardless of size, while list comprehension has O(N) space complexity
1) List comprehension uses less memory
2) Both have identical memory footprints
3) Generator expression stores items in temporary files
Correct Answer:

93. What is a common pitfall when writing generator functions that deal with file handles?

0) If iteration stops early and the generator object is garbage collected without reaching its end, open files might remain unclosed unless managed by a context manager or `try...finally` block inside the generator
1) Generators cannot open files
2) Files are closed automatically on the first yield
3) Generators double the file size in RAM
Correct Answer:

94. How can you ensure proper cleanup (like closing files) inside a generator even if iteration is aborted early?

0) By wrapping the resource acquisition and yielding inside a `try...finally` block inside the generator function
1) By calling `gen.close()` manually every time
2) By using `@functools.cleanup`
3) It is handled automatically by the garbage collector
Correct Answer:

95. What does the `itertools.islice(iterable, start, stop, step)` function do?

0) Returns an iterator that yields selected elements from the iterable based on start, stop, and step indices, similar to list slicing but lazily
1) Slices a list into chunks and returns a new list immediately
2) Deletes elements from an iterable
3) Sorts an iterable by index
Correct Answer:

96. What does `itertools.tee(iterable, n=2)` do?

0) Returns `n` independent independent iterators from a single iterable source
1) Splits an iterable into two halves based on a condition
2) Combines two iterators into a tee tuple
3) Duplicates elements in a generator
Correct Answer:

97. What is a potential memory consideration when using `itertools.tee()` on a large generator?

0) If one iterator advances much faster than the other, `tee` must buffer unconsumed items in memory, potentially increasing memory usage
1) It consumes double the CPU cycles
2) It closes the source generator immediately
3) It raises a MemoryError instantly
Correct Answer:

98. What is the primary design philosophy behind Python's inclusion of generators and decorators?

0) Enhancing code readability, modularity, code reuse, and efficient lazy data processing without boilerplate
1) Maximizing object-oriented inheritance depth
2) Enforcing strict static typing rules
3) Eliminating the need for functions entirely
Correct Answer:

99. Can a decorator take variable positional (`*args`) and keyword (`**kwargs`) arguments to support functions with any signature?

0) Yes, wrapper functions almost universally accept `*args` and `**kwargs` so they can wrap functions with any arbitrary signature
1) No, wrapper functions must match the exact parameter count of the target function
2) Only if using class-based decorators
3) Only if arguments are passed as a single dictionary
Correct Answer:

100. What is the difference between a normal function and a generator function when inspected with `inspect.isgeneratorfunction()`?

0) `inspect.isgeneratorfunction()` returns `True` for generator functions (containing `yield`) and `False` for normal functions
1) It returns `True` for all functions
2) It checks if the function is currently running
3) It checks if the function uses decorators
Correct Answer:
← Previous: Python Control Flow MCQs
Next →: Python Exception / Error Handling MCQs
Python Control Flow MCQs

Python Control Flow MCQs

Control flow statements regulate the order in which individual code statements are evaluated and executed in a Python program. Python…

By MCQs Generator
C++ Variables & Data Types MCQs

C++ Variables & Data Types MCQs

Variables and data types form the core building blocks of any C++ application, defining how data is stored, represented, and…

By MCQs Generator
Python File handlings MCQs

Python File Handling MCQs

Python provides built-in file handling capabilities through the open() function, allowing developers to seamlessly read from, write to, and manipulate…

By MCQs Generator