This quiz tests your understanding of Context Managers in Python tools that help manage resources like files and connections efficiently using the with statement.
Question 1
What is the primary benefit of using the with statement when handling files in Python?
It allows multiple files to be opened simultaneously
It improves file reading speed
It ensures automatic resource cleanup
It adds encryption to file content
Question 2
Which of the following will correctly open and automatically close a file using a context manager?
file = open("data.txt", "r")
with open("data.txt", "r"):
open("data.txt", "r").close()
try open("data.txt", "r"):
Question 3
What happens if a file is not properly closed after being opened in a script?
The file is automatically deleted
You may run out of memory
It could cause resource leakage
Nothing, it always closes automatically
Question 4
What are the required methods in a custom context manager class?
__open__() and __close__()
__start__() and __end__()
__init__() and __cleanup__()
__enter__() and __exit__()
Question 5
What does the __enter__() method typically do in a custom context manager?
Returns a cleanup function
Yields data one item at a time
Acquires the resource and returns it
Closes the file
Question 6
In the following code, what happens after the with block finishes?
with open("log.txt", "w") as file:
file.write("Logging data")
File remains open
File is automatically closed
File data is lost
Exception is raised
Question 7
What does the @contextmanager decorator from contextlib allow?
Manual file handling with error checking
Using generators to create context managers
Converting lists to file objects
Auto-closing all open files
Question 8
What is the output of this context manager class?
class Demo:
def __enter__(self):
print("Enter")
def __exit__(self, *args):
print("Exit")
with Demo():
print("Inside")
Inside
Enter Inside Exit
Enter Exit Inside
Exit Inside
Question 9
What happens if an exception is raised inside a with block managed by a context manager?
The context manager crashes
The file remains open
__exit__() still runs and can handle the error
Python skips cleanup
There are 9 questions to complete.