Junior — Middle
Have you ever programmed functions that extend the behavior of other functions using decorators?
sobes.tech AI
Answer from AI
Yes, in Python, decorators are used to extend or modify the behavior of functions without changing their original code. They are functions that take another function and return a new function with additional logic.
Here's an example of a simple decorator that prints the execution time of a function:
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time of {func.__name__}: {end - start:.4f} seconds")
return result
return wrapper
@timer
def some_function():
time.sleep(1)
some_function()
Here, @timer extends some_function by adding execution time measurement.