Generator-based Context Managers with contextlib
12345678910111213141516171819202122from contextlib import contextmanager @contextmanager def temporary_setting(settings_dict, key, temp_value): original_value = settings_dict.get(key) settings_dict[key] = temp_value try: yield finally: if original_value is None: del settings_dict[key] else: settings_dict[key] = original_value # Usage settings = {"theme": "dark", "volume": 80} print("Before:", settings) with temporary_setting(settings, "theme", "light"): print("Inside context:", settings) print("After:", settings)
The contextlib.contextmanager decorator lets you write a context manager using a generator function. This approach simplifies resource management when you only need to set up and tear down resources, without needing a full class. In the code sample above, the temporary_setting function changes a value in a dictionary for the duration of the context and then restores the original value.
When you use the @contextmanager decorator, the function you write must be a generator, meaning it must use the yield statement. Everything before yield runs when entering the context (the code inside the with block). Everything after yield runs when exiting the context, even if an exception occurs. The try...finally structure ensures that the cleanup code always runs. This pattern is ideal for temporary changes—such as modifying a setting, opening a resource, or changing an environment variable—and then reliably undoing those changes afterward.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Can you explain how the `temporary_setting` context manager works step by step?
What are some other use cases for the `@contextmanager` decorator?
How does this approach compare to writing a full context manager class?
Awesome!
Completion rate improved to 8.33
Generator-based Context Managers with contextlib
Desliza para mostrar el menú
12345678910111213141516171819202122from contextlib import contextmanager @contextmanager def temporary_setting(settings_dict, key, temp_value): original_value = settings_dict.get(key) settings_dict[key] = temp_value try: yield finally: if original_value is None: del settings_dict[key] else: settings_dict[key] = original_value # Usage settings = {"theme": "dark", "volume": 80} print("Before:", settings) with temporary_setting(settings, "theme", "light"): print("Inside context:", settings) print("After:", settings)
The contextlib.contextmanager decorator lets you write a context manager using a generator function. This approach simplifies resource management when you only need to set up and tear down resources, without needing a full class. In the code sample above, the temporary_setting function changes a value in a dictionary for the duration of the context and then restores the original value.
When you use the @contextmanager decorator, the function you write must be a generator, meaning it must use the yield statement. Everything before yield runs when entering the context (the code inside the with block). Everything after yield runs when exiting the context, even if an exception occurs. The try...finally structure ensures that the cleanup code always runs. This pattern is ideal for temporary changes—such as modifying a setting, opening a resource, or changing an environment variable—and then reliably undoing those changes afterward.
¡Gracias por tus comentarios!