Decorators Flashcards

1
Q

Simple decorator

A
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()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Decorator to measure execution time

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Logging function calls

A

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”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Decorator with argument

A

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”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Chaining decorators

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly