Bird
0
0

You want to write a context manager that logs when a file is opened and closed. Which method must you implement to ensure the file closes even if an error occurs?

hard📝 Application Q8 of 15
Python - Context Managers
You want to write a context manager that logs when a file is opened and closed. Which method must you implement to ensure the file closes even if an error occurs?
A__exit__
B__enter__
C__init__
D__open__
Step-by-Step Solution
Solution:
  1. Step 1: Understand context manager methods

    Custom context managers implement __enter__ to start and __exit__ to clean up resources.
  2. Step 2: Identify method for closing on errors

    The __exit__ method runs even if exceptions occur, so it handles closing safely.
  3. Final Answer:

    __exit__ -> Option A
  4. Quick Check:

    __exit__ handles cleanup and errors [OK]
Quick Trick: __exit__ method cleans up resources safely [OK]
Common Mistakes:
  • Confusing __enter__ with cleanup
  • Thinking __init__ manages resource closing
  • Assuming __open__ is a valid method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes