Python with statement — Context manager protocol and file I/O
Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)
Quick Answer
The answer is that the 'with' statement can be used with any object implementing the context manager protocol, not just files. This is correct because the protocol requires only the __enter__ and __exit__ methods, which the 'with' statement automatically calls to set up and tear down resources, making it a clean alternative to try/finally blocks. On the PCAP exam, this concept tests your understanding of resource management beyond file I/O, often appearing in questions that ask you to identify valid uses or spot the false statement about the protocol. A common trap is assuming the 'with' statement only works with files, but it works with database connections, locks, and network sockets too. For the exam, remember that the 'with' statement can also handle multiple context managers in one line, separated by commas, which is a frequently tested detail. Memory tip: think of __enter__ as "setup" and __exit__ as "cleanup" — if an object has both, it's ready for 'with'.
⚠ Common exam trap
Python Institute often tests the misconception that the 'with' statement is only for file I/O, leading candidates to incorrectly select option E, while also testing the understanding that it simplifies but does not replace try/finally blocks, making option D a distractor for those who overestimate its capabilities.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
It can be used with any object that implements __enter__ and __exit__ methods.
Option A is correct because the context manager protocol is defined precisely by the presence of __enter__ and __exit__ methods, so any object implementing both can be used with 'with'. Option B is correct because the 'with' statement's semantics ensure __exit__ is invoked when the block exits, whether normally or via an exception, which is the core guarantee of the protocol. Option C is correct because Python supports 'with A() as a, B() as b:' syntax, allowing multiple context managers separated by commas (equivalent to nested with statements). Option D is not marked correct because while 'with' often replaces try/finally for resource cleanup, it does not eliminate the need for try/finally in all cases, such as when no context manager exists or when cleanup logic must run without one. Option E is not marked correct because 'with' works with any context manager, not only file objects; files are just a common example.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
It can be used with any object that implements __enter__ and __exit__ methods.
Why this is correct
The 'with' statement works with any object implementing the context manager protocol, namely __enter__ and __exit__. This duck-typing behaviour means files, locks, sockets and custom classes all qualify, without requiring inheritance from a specific base class.
- ✓
It guarantees that the __exit__ method is called even if an exception occurs inside the block.
Why this is correct
The context manager protocol routes exceptions through __exit__, which runs during unwinding whether the block completes normally or raises. This guaranteed cleanup is the mechanism that makes 'with' preferable to manual try/finally for releasing resources.
- ✓
It can be used with multiple context managers separated by commas.
Why this is correct
Python's grammar permits a comma-separated list of context managers in a single `with` statement, such as `with open(a) as f, open(b) as g:`. Each manager's `__enter__` runs left to right, and exits run in reverse order, satisfying the stem's requirement for a true statement about the `with` statement.
- ✗
It eliminates the need for try/finally blocks for resource management.
Why it's wrong here
The with statement does not remove try/finally; it is implemented via context managers whose __exit__ runs on exception, and try/finally remains valid and sometimes necessary. It tempts because with does replace the common open/close try/finally idiom, which is the correct choice for simple deterministic cleanup.
- ✗
It can only be used with file objects.
Why it's wrong here
Any object implementing __enter__ and __exit__ works with with, including locks, sockets, database connections and contextlib helpers. It tempts because file handling is the canonical teaching example, and with is indeed correct when managing file descriptors, but the protocol is general, not file-specific.
Go deeper
Related to this question
About these practice questions
One of 421 original PCAP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
Same concept, more angles
4 more ways this is tested on PCAP
These questions test the same concept from different angles. Work through them to make sure you can recognise it however the exam phrases it.
Variation 1. Which TWO of the following are correct statements about the 'with' statement in Python file I/O?
easy- ✓ A.It ensures the file is closed when the block exits.
- B.It can only be used with file objects.
- C.It automatically opens the file without needing open().
- ✓ D.It ensures that resources are released even if an exception is raised.
- E.It prevents any exception from occurring during file operations.
Why A: The 'with' statement in Python acts as a context manager that automatically calls the file object's __exit__ method when the block exits, which in turn invokes the file's close() method. This guarantees that the file is properly closed, even if an exception occurs within the block, ensuring deterministic resource cleanup.
Variation 2. Which TWO of the following are true about the 'with' statement in Python file I/O?
medium- A.It can only be used with file objects
- ✓ B.It is equivalent to a try/finally block
- ✓ C.It automatically closes the file after the block
- D.It does not require an __exit__ method
- E.It requires the object to have an __enter__ method only
Why B: The 'with' statement in Python is designed to simplify exception handling by encapsulating the setup and teardown of a resource in a context manager, which is functionally equivalent to a try/finally block. When you use 'with', the context manager's __exit__ method is guaranteed to be called even if an exception occurs, ensuring that cleanup actions like closing a file are performed, just as a finally clause would.
Variation 3. Which THREE of the following are true about the `with` statement for file handling?
hard- A.It can only be used with files.
- B.It can only handle one file at a time.
- ✓ C.It uses the __enter__ and __exit__ methods of the file object.
- ✓ D.It ensures the file is closed even if an exception occurs inside the block.
- ✓ E.It automatically closes the file when the block exits.
Why C: The `with` statement relies on the context management protocol, which requires the object to implement the `__enter__` and `__exit__` methods. When a file object is used with `with`, its `__enter__` method returns the file object itself, and its `__exit__` method is called upon block exit to handle cleanup, such as closing the file.
Variation 4. A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?
medium- A.Use try/finally with explicit f.close()
- B.Rely on the garbage collector to close the file
- C.Use try/except/finally with f.close() in both except and finally
- ✓ D.Use the with statement: with open('file.txt', 'w') as f: ...
Why D: The `with` statement in Python implements a context manager that automatically calls the file's `__exit__` method, which closes the file even if an exception occurs inside the block. This is the idiomatic and recommended approach for resource management, as it guarantees cleanup without requiring explicit `close()` calls.
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCAP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCAP exam.