Sobes.tech
Junior — Middle

How to implement an automatic resource management mechanism in Python using classes?

sobes.tech AI

Answer from AI

In Python, the context manager protocol, implemented by the __enter__ and __exit__ methods in a class, is used for automatic resource management.

When using the with statement, the __enter__ method is called upon entering the block, and __exit__ is called upon exiting, even if an exception occurs inside the block. This guarantees resource release.

Example of a class with automatic resource management:

class ManagedResource:
    def __enter__(self):
        print("Resource opened")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Resource closed")
        # Exceptions can be handled here if needed

# Usage
with ManagedResource() as resource:
    print("Working with resource")

The output will be:

Resource opened
Working with resource
Resource closed

Thus, by implementing __enter__ and __exit__, you can create classes that automatically manage resources.