Junior — Middle
Is it possible to implement a custom context manager in Python without using built-in tools?
sobes.tech AI
Answer from AI
Yes, it is possible to implement a custom context manager in Python without using built-in features (with and __enter__/__exit__ methods). You can create a class with methods for explicit resource management, such as start() and stop(), and use them manually.
Example:
class MyContextManager:
def __init__(self):
self.resource = None
def start(self):
print("Resource opened")
self.resource = "Active resource"
def stop(self):
print("Resource closed")
self.resource = None
# Usage
mgr = MyContextManager()
mgr.start()
# work with the resource
print(mgr.resource)
mgr.stop()
This way, you manually control the resource's lifecycle, but do not use the with syntax. However, the built-in context manager is more convenient and safer, as it guarantees resource release even in case of exceptions.