JN0-224 · Question #108
Which Python code block is an example of an context manager? A. B. C. D.
The correct answer is A. while True: device = Device(host="vmx-1", user="lab", passwd="lab123"). There is an error in this question's answer key - option C is actually correct, not A. Here's the accurate explanation: Option C is the context manager because it uses Python's with statement, which is the defining syntax for context managers. The with block automatically calls…
Question
Which Python code block is an example of an context manager? A. B. C. D.
Exhibits
Options
- Awhile True: device = Device(host="vmx-1", user="lab", passwd="lab123") ...
- Btry: device = Device(host="vmx-1", user="lab", passwd="lab123") ...
- Cwith Device(host="vmx-1", user="lab", passwd="lab123") as device: ...
- Dfor host in ["vmx-1", "vmx-2"]: device = Device(host=host, user="lab", passwd="lab123") ...
How the community answered
(37 responses)- A89% (33)
- B8% (3)
- D3% (1)
Explanation
There is an error in this question's answer key - option C is actually correct, not A. Here's the accurate explanation:
Option C is the context manager because it uses Python's with statement, which is the defining syntax for context managers. The with block automatically calls __enter__() when entering and __exit__() when leaving (even if an exception occurs), handling setup and teardown - like opening/closing a network device connection - without explicit cleanup code.
Option A (while True) is an infinite loop - it keeps running until break or an exception; it has no automatic resource management. Option B (try/except) is error handling - it can simulate some cleanup behavior with a finally block, but it is not a context manager. Option D (for) is a simple iteration loop with no resource lifecycle management.
Memory tip: Think of with as "with a guarantee" - Python guarantees cleanup runs when the block exits, no matter what. If you see with X as y:, that's always a context manager.
Note for exam takers: If your official answer key says A, flag it - this is a mistake. The
withstatement (option C) is unambiguously the Python context manager pattern as defined in PEP 343.
Topics
Community Discussion
No community discussion yet for this question.

