Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Creating Custom Context Managers | Advanced File Handling & Context Managers
Python Structural Programming

Creating Custom Context Managers

Deslize para mostrar o menu

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.

question mark

Which statement best describes the role of the __exit__ method in a custom context manager?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 2. Capítulo 5
some-alt