Python Programming - Decorators

Exercise : Decorators - General Questions
  • Decorators - General Questions
21.
What is the purpose of the @functools.retry decorator?
Retries a function with a specified delay in case of failure
Converts a method to a class method
Decorates a method with dynamic behavior
Provides a way to document and maintain the original function's metadata
Answer: Option
Explanation:
The @functools.retry decorator is used to retry a function with a specified delay in case of failure.
@functools.retry(max_retries=3, delay=2)
def unstable_function():
    # Function implementation

22.
What is the purpose of the @functools.singledispatchmethod decorator?
Converts a method to a class method
Enables function overloading based on argument types
Marks a method as a static method
Decorates a method with dynamic behavior
Answer: Option
Explanation:
The @functools.singledispatchmethod decorator in Python is used to enable function overloading based on the type of the first argument within a class.

23.
What does the @functools.cached_property decorator do when applied to a method inside a class?
Converts the method to a class method
Marks the method as a static method
Caches the result of the method and returns the cached value
Decorates the method with dynamic behavior
Answer: Option
Explanation:
The @functools.cached_property decorator caches the result of a method and returns the cached value on subsequent calls.

24.
How does the @functools.singledispatch decorator differ from @functools.singledispatchmethod?
@functools.singledispatch is used for functions, while @functools.singledispatchmethod is used for methods.
@functools.singledispatch is used for static methods, while @functools.singledispatchmethod is used for instance methods.
@functools.singledispatch is used for class-level attribute access, while @functools.singledispatchmethod is used for dynamic method invocation.
There is no difference; they serve the same purpose.
Answer: Option
Explanation:
@functools.singledispatch is used for functions, providing a mechanism for function overloading based on argument types, while @functools.singledispatchmethod serves the same purpose but is specifically designed for methods within a class.

25.
What is the primary purpose of the @functools.cached_property decorator?
Caches the results of function calls to improve performance
Converts a method to a class method
Declares an abstract method in a Python class
Marks a method as a static method
Answer: Option
Explanation:
The @functools.cached_property decorator is used to cache the result of a method and return the cached value on subsequent calls, improving performance by avoiding redundant computations.