#9 – Niche Features Flashcards

(12 cards)

1
Q

What is a decorator in Python?

A

A decorator is a function that modifies another function or method. It uses @ syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you write a simple decorator?

A

Define a function that returns a wrapper function.

def decorator(func):     def wrapper():         print('Before')         func()         print('After')     return wrapper
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you apply a decorator?

A

Use @decorator_name above the function.

@decorator def greet():     print('Hi')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a generator in Python?

A

A generator is a function that yields values one at a time using yield, maintaining state between calls.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you define a generator function?

A

Use yield instead of return.

def count_up():     yield 1     yield 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you get values from a generator?

A

Use next() or loop over it.

gen = count_up() next(gen)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a context manager?

A

An object that defines \_\_enter\_\_ and \_\_exit\_\_ methods, often used with with to manage resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you use a context manager?

A

With the with statement.

with open('file.txt') as f:     data = f.read()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you define a custom context manager?

A

Use a class with \_\_enter\_\_ and \_\_exit\_\_, or use the contextlib module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a list comprehension?

A

A compact way to create lists.

[x*2 for x in range(5)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you write a list comprehension with condition?

A

Add an if clause.

[x for x in range(5) if x % 2 == 0]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What makes Python unique compared to many other languages?

A

Its emphasis on readability, dynamic typing, strong community, and support for multiple paradigms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly