Creating Custom Context Managers
Veeg om het menu te tonen
To fully harness the power of context managers in Python, you can create your own by defining a class that implements the __enter__ and __exit__ methods. The __enter__ method is called when execution enters the context of the with statement, and its return value is assigned to the variable after as. The __exit__ method is invoked when execution leaves the context, regardless of whether it exits normally or due to an exception. This design allows you to set up and tear down resources safely and predictably, which is especially useful for managing files, network connections, or locks.
The __exit__ method receives three arguments: exc_type, exc_value, and traceback. These provide details about any exception that occurred within the context block. If __exit__ returns True, it suppresses the exception; otherwise, the exception will propagate after cleanup. By implementing these methods, you can precisely control the setup and cleanup logic for your resource, making your code more robust and maintainable.
class FileLogger:
def __init__(self, filename, logname):
self.filename = filename
self.logname = logname
self.file = None
self.log = None
def __enter__(self):
self.file = open(self.filename, "r")
self.log = open(self.logname, "a")
self.log.write(f"Opened file: {self.filename}\n")
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
self.log.write(f"Closed file: {self.filename}\n")
if self.log:
self.log.close()
# Do not suppress exceptions
return False
The following code demonstrates a custom context manager class FileLogger. This class is designed to open a target file for reading and a log file for appending log entries. When entering the context (using the with statement), it logs the file opening event. When exiting the context - whether due to normal execution or an exception - it logs the file closing event and ensures both files are properly closed. The __exit__ method does not suppress exceptions, allowing them to propagate after cleanup.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.