Decorators Flashcards
Simple decorator
def simple_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @simple_decorator def say_hello(): print("Hello!") say_hello()
Decorator to measure execution time
def timer_decorator(func):
def wrapper(args, **kwargs):
start_time = time.time()
result = func(args, **kwargs)
end_time = time.time()
print(f”Function {func.__name__} took {end_time - start_time} seconds to run.”)
return result
return wrapper
@timer_decorator
def long_running_function():
time.sleep(2)
print(“This function takes a while!”)
long_running_function()
Logging function calls
def logging_decorator(func):
def wrapper(args, **kwargs):
print(f”Called {func.__name__} with {args} and {kwargs}.”)
return func(args, **kwargs)
return wrapper
@logging_decorator
def greet(name, greeting=”Hello”):
print(f”{greeting}, {name}.”)
greet(“Alice”, greeting=”Howdy”)
Decorator with argument
def repeat(num_times):
def decorator_repeat(func):
def wrapper(args, **kwargs):
for _ in range(num_times):
func(args, **kwargs)
return wrapper
return decorator_repeat
@repeat(3)
def greet(name):
print(f”Hello {name}”)
greet(“Python”)
Chaining decorators
def decorator_1(func):
def wrapper():
print(“Decorator 1 executed”)
func()
return wrapper
def decorator_2(func):
def wrapper():
print(“Decorator 2 executed”)
func()
return wrapper
@decorator_1
@decorator_2
def hello():
print(“Hello, world!”)
hello()