Sobes.tech
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.

  • with statement — a syntactic construct that simplifies working with context managers by automatically calling __enter__() and __exit__() methods.

  • __enter__() method — called when entering a with block, usually initializes the resource and returns it.

  • __exit__() method — called when exiting a with block, 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.