FlashKeepers

Python · Python · College and University

Python Decorators and Generators

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

About this set

30 basic cards for Python Python. It opens with "What is a Python decorator?" and "What does the @ symbol do when placed before a function name?". More College and University decks are listed below.

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

Study this set free Look inside first Get FlashKeepers for iPhone

Opens in your browser, no account. Get the iPhone and iPad app · Android app

What is a Python decorator?
Show answerA 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?
Show answerIt applies a decorator to the function, equivalent to func = decorator(func).
Can multiple decorators be applied to a single function?
Show answerYes, they can be stacked. They execute from bottom to top when applied.
What is the purpose of functools.wraps in a decorator?
Show answerIt preserves the original function's metadata, including __name__ and __doc__, on the wrapper function.
What is a parameterized decorator?
Show answerA 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.
Show answerdef my_decorator(func): def wrapper(*args, **kwargs): print('Starting'); return func(*args, **kwargs); return wrapper
Can you decorate a class with a decorator?
Show answerYes, class decorators can modify class attributes, methods, or return an entirely different class.
When two decorators are stacked, which one's wrapper executes first?
Show answerThe 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?
Show answerTo allow the decorator to work with functions of any signature without knowing their exact parameters.
What is a generator function?
Show answerA function that uses the yield keyword to return values one at a time, preserving state between calls.
What does the yield keyword do?
Show answerIt 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?
Show answerA generator object (an iterator), not the first yielded value.
How do you retrieve values from a generator?
Show answerUse next() on the generator object, or iterate over it with a for loop.
What exception is raised when a generator is exhausted?
Show answerStopIteration, indicating no more values are available.
What is a generator expression?
Show answerA 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

Study this set free