#9 – Niche Features Flashcards
(12 cards)
What is a decorator in Python?
A decorator is a function that modifies another function or method. It uses @
syntax.
How do you write a simple decorator?
Define a function that returns a wrapper function.
def decorator(func): def wrapper(): print('Before') func() print('After') return wrapper
How do you apply a decorator?
Use @decorator_name
above the function.
@decorator def greet(): print('Hi')
What is a generator in Python?
A generator is a function that yields values one at a time using yield
, maintaining state between calls.
How do you define a generator function?
Use yield
instead of return
.
def count_up(): yield 1 yield 2
How do you get values from a generator?
Use next()
or loop over it.
gen = count_up() next(gen)
What is a context manager?
An object that defines \_\_enter\_\_
and \_\_exit\_\_
methods, often used with with
to manage resources.
How do you use a context manager?
With the with
statement.
with open('file.txt') as f: data = f.read()
How do you define a custom context manager?
Use a class with \_\_enter\_\_
and \_\_exit\_\_
, or use the contextlib
module.
What is a list comprehension?
A compact way to create lists.
[x*2 for x in range(5)]
How do you write a list comprehension with condition?
Add an if
clause.
[x for x in range(5) if x % 2 == 0]
What makes Python unique compared to many other languages?
Its emphasis on readability, dynamic typing, strong community, and support for multiple paradigms.