Context Managers Flashcards

(10 cards)

1
Q

What is a context manager?

A

A construct that automatically handles setup and cleanup of resources using the with statement

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

Why use the with statement?

A

Ensures resources (files, connections) are properly closed, even if an error occurs.

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

What happens internally in a with block?

A

Calls __enter__()

Executes block

Calls __exit__() (even on exception)

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

What does __enter__ do?

A

Runs at the start and returns the resource used inside the block.

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

What does __exit__ do?

A

Runs at the end, handles cleanup, and executes even if an error occurs.

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

How does a context manager handle exceptions?

A

__exit__ receives exception details and still performs cleanup.

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

What is contextmanager used for?

A

To create context managers using a generator and yield instead of a class.

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

In contextmanager, what does yield represent?

A

Before yield → setup (__enter__)

After yield → cleanup (__exit__)

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

Where are context managers used?

A

File handling, DB connections, locks, network resources.

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