What is Python’s Context Manager?
a) A way to manage resources such as file streams using the with statement
b) A tool for debugging Python code
c) A method for managing global variables
d) A feature that helps in garbage collection
Answer:
a) A way to manage resources such as file streams using the with statement
Explanation:
Python’s context managers provide a way to manage resources, such as file streams, sockets, or database connections, ensuring that they are properly acquired and released. Context managers are commonly used with the with
statement to guarantee that resources are automatically cleaned up, even if an error occurs.
# Using a context manager to open a file
with open("example.txt", "w") as file:
file.write("Hello, World!")
In this example, the file is opened using a context manager, and once the block of code under the with
statement is executed, the file is automatically closed, even if an exception is raised.
Context managers are essential for resource management, helping to prevent resource leaks and making code cleaner and more reliable.