Exercise: Python

Questions for: Decorators

How does the @contextlib.asynccontextmanager decorator differ from @contextlib.contextmanager?
A:
@contextlib.asynccontextmanager is used for asynchronous context managers.
B:
@contextlib.asynccontextmanager is used for synchronous context managers.
C:
There is no difference; they serve the same purpose.
D:
@contextlib.contextmanager is used for decorators.
Answer: A
@contextlib.asynccontextmanager is specifically designed for creating asynchronous context managers, allowing the use of the 'async with' statement.
How does the @functools.partialmethod decorator differ from @functools.partial?
A:
@functools.partialmethod is applied to methods, while @functools.partial is applied to functions.
B:
@functools.partialmethod is used for class-level attribute access.
C:
@functools.partialmethod is used for dynamic method invocation.
D:
@functools.partialmethod is used to create partially-applied functions with fixed arguments.
Answer: A
@functools.partialmethod is specifically designed for methods in a class, allowing for partial application of arguments, while @functools.partial is used for functions in general.
What does the @functools.cmp_to_key decorator do?
A:
Converts a method to a class method
B:
Enables the use of the 'with' statement for resource management
C:
Converts an old-style comparison function to a key function
D:
Marks a method as a static method
Answer: C
The @functools.cmp_to_key decorator is used to convert an old-style comparison function to a key function, making it compatible with functions that require a key for comparison.
What is the primary purpose of the @contextlib.contextmanager decorator?
A:
Converts a method to a class method
B:
Enables the use of the 'with' statement for resource management
C:
Marks a method as a static method
D:
Decorates a method with dynamic behavior
Answer: B
The @contextlib.contextmanager decorator is used to define a generator-based context manager, enabling the use of the 'with' statement for resource management.
What is the primary purpose of the @functools.cached_property decorator?
A:
Caches the results of function calls to improve performance
B:
Converts a method to a class method
C:
Declares an abstract method in a Python class
D:
Marks a method as a static method
Answer: A
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.
Ad Slot (Above Pagination)
Quiz