Sobes.tech
Junior — Middle

What methods should be implemented in a class to support the with statement in Python?

sobes.tech AI

Answer from AI

To support the with statement in Python, a class must implement the context manager protocol, which means defining the following methods:

  • __enter__(self) — called when entering the with block. Typically, resources are initialized here.
  • __exit__(self, exc_type, exc_val, exc_tb) — called when exiting the with block, even if an exception occurs inside. Resources are usually released here.

Example:

class ManagedFile:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

with ManagedFile('example.txt') as f:
    data = f.read()

By implementing these two methods, you can use an object of the class within a with statement for automatic resource management.

What methods should be implemented in a class to… - sobes.tech