Sobes.tech
Senior

Have you used decorators and generators in your work? What is a decorator and why is it needed?

sobes.tech AI

Answer from AI

Yes, I have used both decorators and generators.

Decorator — is a function that takes another function and returns a new function with extended behavior, without modifying the original code. It is useful for adding logging, permission checks, caching, and other aspects.

Example of a decorator in Python:

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs)
        print("After calling the function")
        return result
    return wrapper

@decorator
def say_hello():
    print("Hello")

say_hello()

Generators — are functions that return an iterator and allow iterating over a sequence of values using yield. They save memory because they do not create the entire collection at once.

Example of a generator:

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)

In testing, decorators help create universal wrappers for tests, and generators are used for creating data streams or parameterization.