Junior — Middle
What is the purpose of annotations with '@' in Python, and how do they work?
sobes.tech AI
Answer from AI
In Python, the '@' symbol is used for declaring decorators — special functions that modify the behavior of other functions or classes. The decorator is placed before the function or class definition and applies to that object.
A decorator takes a function (or class) as an argument, can modify or wrap it, and then returns a new function (or class).
Example:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Before function call
Hello!
After function call
Thus, decorators with '@' allow for easy and readable modification of functions and classes' behavior.