FlashKeepers

Python · Python

Python Decorators and Generators

Function decorators, generator functions, and the yield keyword, each explained with a short example.

30 cards · basic cards · AI-written, checked twice. Edit anything.

Study this set free Look inside first Get FlashKeepers for iPhone
What is a Python decorator?
A function that wraps another function or class to modify its behavior without permanently changing the original.
What does the @ symbol do when placed before a function name?
It applies a decorator to the function, equivalent to func = decorator(func).
Can multiple decorators be applied to a single function?
Yes, they can be stacked. They execute from bottom to top when applied.
What is the purpose of functools.wraps in a decorator?
It preserves the original function's metadata, including __name__ and __doc__, on the wrapper function.
What is a parameterized decorator?
A decorator that accepts arguments to configure its behavior before decorating the target function.
Write a simple decorator that adds a print statement before a function runs.
def my_decorator(func): def wrapper(*args, **kwargs): print('Starting'); return func(*args, **kwargs); return wrapper
Can you decorate a class with a decorator?
Yes, class decorators can modify class attributes, methods, or return an entirely different class.
When two decorators are stacked, which one's wrapper executes first?
The top decorator's wrapper executes first, but the bottom decorator was applied last to the original function.
Why should a decorator preserve *args and **kwargs?
To allow the decorator to work with functions of any signature without knowing their exact parameters.
What is a generator function?
A function that uses the yield keyword to return values one at a time, preserving state between calls.
What does the yield keyword do?
It pauses the function, returns a value to the caller, and resumes execution from that point on the next call.
What does calling a generator function return?
A generator object (an iterator), not the first yielded value.
How do you retrieve values from a generator?
Use next() on the generator object, or iterate over it with a for loop.
What exception is raised when a generator is exhausted?
StopIteration, indicating no more values are available.
What is a generator expression?
A generator created inline using syntax like (x**2 for x in range(10)), with parentheses instead of square brackets.

15 more cards in the app