Junior — Middle
Can you explain how to implement a decorator that does not use parameters?
sobes.tech AI
Answer from AI
A parameterless decorator is a function that takes another function and returns a new function with additional behavior. Here's an example of a simple decorator that prints a message before calling the function:
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Calling function...")
return func(*args, **kwargs)
return wrapper
@simple_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
Here, simple_decorator does not take any parameters other than the function it decorates. Inside, a nested function wrapper is created, which adds the desired behavior and calls the original function.