Python Programming - Decorators

Exercise : Decorators - General Questions
  • Decorators - General Questions
6.
Which decorator can be used to measure the execution time of a Python function?
@functools.lru_cache
@functools.singledispatch
@functools.wraps
@functools.timer
Answer: Option
Explanation:
There is no built-in @functools.timer decorator in Python, but a custom timer decorator can be created using external libraries or by measuring time manually.

7.
What is the primary purpose of the @functools.singledispatch decorator?
Converts a method to a class method
Enables function overloading based on argument types
Indicates a method is an instance method
Decorates a method with dynamic behavior
Answer: Option
Explanation:
The @functools.singledispatch decorator in Python is used to enable function overloading based on the type of the first argument.

8.
Which decorator is used to ensure that a function is only executed after a certain condition is met?
@functools.lru_cache
@functools.wraps
@functools.singledispatch
@functools.singledispatchmethod
Answer: Option
Explanation:
There is no built-in @functools.singledispatchmethod decorator in Python, but a custom decorator can be created to execute a function based on a specified condition.

9.
How can you create a decorator that takes arguments?
Using the @staticmethod decorator
Using the @functools.wraps decorator
By defining a higher-order function that returns the actual decorator
By using the @classmethod decorator
Answer: Option
Explanation:
To create a decorator that takes arguments, you can define a higher-order function that returns the actual decorator based on the provided arguments.

10.
When using the @functools.lru_cache decorator, what is the purpose of the maxsize parameter?
Sets the maximum number of cache entries
Controls the cache eviction policy
Determines the cache timeout duration
Specifies the maximum recursion depth for caching
Answer: Option
Explanation:
The maxsize parameter in the @functools.lru_cache decorator specifies the maximum number of entries to be stored in the cache. Once this limit is reached, older entries are evicted.