Junior — Middle
Can you name the main terms related to the use of the context manager?
sobes.tech AI
Answer from AI
Key terms related to the use of context managers in Python:
-
Context Manager — an object that defines
__enter__()and__exit__()methods. It manages resources, ensuring they are properly opened and closed. -
withstatement — a syntactic construct that simplifies working with context managers by automatically calling__enter__()and__exit__()methods. -
__enter__()method — called when entering awithblock, usually initializes the resource and returns it. -
__exit__()method — called when exiting awithblock, responsible for releasing resources and handling exceptions.
Example:
with open('file.txt', 'r') as f:
data = f.read()
Here, open() returns a context manager that automatically closes the file after exiting the block.