Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Class-based Custom Context Managers | Custom Context Managers
Python Context Managers

bookClass-based Custom Context Managers

When you need to manage resources that require setup and cleanup—such as files, network connections, or locks—you can create your own context managers using classes. To design a class-based context manager, define a class that implements both the __enter__ and __exit__ methods. The __enter__ method is called when entering the with block and is responsible for acquiring the resource or performing any setup. The __exit__ method is called when exiting the block, regardless of whether an exception occurred, and is responsible for releasing the resource or performing cleanup.

It is best practice to ensure that resource acquisition happens in __enter__ and cleanup happens in __exit__. The __exit__ method accepts three arguments: the exception type, exception value, and traceback. This allows your context manager to handle exceptions gracefully. If you want to suppress an exception, return True from __exit__; otherwise, return None or False to propagate the exception. Always make sure that __exit__ performs cleanup even if an error occurs inside the with block.

123456789101112131415161718192021222324
class NetworkConnection: def __init__(self, host): self.host = host self.connected = False def __enter__(self): print(f"Connecting to {self.host}...") self.connected = True return self def __exit__(self, exc_type, exc_val, exc_tb): if self.connected: print(f"Disconnecting from {self.host}.") self.connected = False if exc_type: print(f"An exception occurred: {exc_val}") # Do not suppress exceptions return False with NetworkConnection("example.com") as conn: print("Connection in use.") # Uncomment the next line to simulate an error # raise RuntimeError("Network error")
copy

In this example, the NetworkConnection class simulates connecting to and disconnecting from a network resource. The __enter__ method sets up the connection, and the __exit__ method ensures cleanup, handling exceptions if they occur inside the with block. Returning False from __exit__ means exceptions will not be suppressed.

question mark

Which of the following is the correct way to implement the __exit__ method to ensure cleanup and propagate exceptions in a class-based context manager?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 1

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 8.33

bookClass-based Custom Context Managers

Desliza para mostrar el menú

When you need to manage resources that require setup and cleanup—such as files, network connections, or locks—you can create your own context managers using classes. To design a class-based context manager, define a class that implements both the __enter__ and __exit__ methods. The __enter__ method is called when entering the with block and is responsible for acquiring the resource or performing any setup. The __exit__ method is called when exiting the block, regardless of whether an exception occurred, and is responsible for releasing the resource or performing cleanup.

It is best practice to ensure that resource acquisition happens in __enter__ and cleanup happens in __exit__. The __exit__ method accepts three arguments: the exception type, exception value, and traceback. This allows your context manager to handle exceptions gracefully. If you want to suppress an exception, return True from __exit__; otherwise, return None or False to propagate the exception. Always make sure that __exit__ performs cleanup even if an error occurs inside the with block.

123456789101112131415161718192021222324
class NetworkConnection: def __init__(self, host): self.host = host self.connected = False def __enter__(self): print(f"Connecting to {self.host}...") self.connected = True return self def __exit__(self, exc_type, exc_val, exc_tb): if self.connected: print(f"Disconnecting from {self.host}.") self.connected = False if exc_type: print(f"An exception occurred: {exc_val}") # Do not suppress exceptions return False with NetworkConnection("example.com") as conn: print("Connection in use.") # Uncomment the next line to simulate an error # raise RuntimeError("Network error")
copy

In this example, the NetworkConnection class simulates connecting to and disconnecting from a network resource. The __enter__ method sets up the connection, and the __exit__ method ensures cleanup, handling exceptions if they occur inside the with block. Returning False from __exit__ means exceptions will not be suppressed.

question mark

Which of the following is the correct way to implement the __exit__ method to ensure cleanup and propagate exceptions in a class-based context manager?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 1
some-alt