# with ensures cleanup happens even if errors occurclassManagedFile:
def__init__(self, name):
self.name = name
def__enter__(self):
print(f"Opening {self.name}")
return self
def__exit__(self, exc_type, exc_val, exc_tb):
print(f"Closing {self.name}")
returnFalsewith ManagedFile("data.txt") as f:
print(f"Working with {f.name}")
print("File is now closed")
Output
Click "Run" to execute your code
'with' calls __enter__ at the start and __exit__ at the end, guaranteeing cleanup even if exceptions occur.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?