Python Programming - Decorators

Exercise : Decorators - General Questions
  • Decorators - General Questions
16.
Which decorator is commonly used for retrying a function with a specified delay in case of failure?
@functools.retry
@functools.retry_on_fail
@functools.retriable
@functools.retry_with_delay
Answer: Option
Explanation:
There is no built-in @functools.retry decorator in Python, but custom decorators can be created for retrying a function with a specified delay in case of failure.

17.
How does the @property decorator differ from the @staticmethod decorator?
@property is used for dynamic property access, while @staticmethod is used for class-level attribute access.
@property is used to define read-only properties, while @staticmethod is used to convert a method to a class method.
@property is used for dynamic method invocation, while @staticmethod is used to indicate a method is an instance method.
@property is used to convert a method to a class method, while @staticmethod is used for dynamic method invocation.
Answer: Option
Explanation:
@property is used to define read-only properties without the need for explicit getter methods. @staticmethod is used to mark a method as a static method within a class.

18.
Which decorator is commonly used for rate-limiting function calls?
@functools.ratelimit
@functools.limitrate
@functools.ratelimiter
@functools.limitcalls
Answer: Option
Explanation:
There is no built-in @functools.ratelimit decorator in Python, but custom decorators can be created for rate-limiting function calls.

19.
What is the purpose of the @functools.lru_cache decorator's typed parameter?
It enforces strong typing for the cached values.
It uses a different cache for each data type.
It enables caching for functions with different argument types.
It specifies the maximum size of the cache.
Answer: Option
Explanation:
The @functools.lru_cache decorator's typed parameter, when set to True, uses a different cache for each distinct data type, preventing collisions between values of different types.

20.
What is the primary purpose of the @functools.total_ordering decorator?
Converts a method to a class method
Enables automatic generation of rich comparison methods
Marks a method as a static method
Decorates a method with dynamic behavior
Answer: Option
Explanation:
The @functools.total_ordering decorator is used to automatically generate rich comparison methods (e.g., __eq__, __lt__) based on a minimal set of comparison methods provided in the class.
@functools.total_ordering
class MyClass:
    def __init__(self, value):
        self.value = value
    
    def __eq__(self, other):
        return self.value == other.value
    
    def __lt__(self, other):
        return self.value < other.value