Bird
Raised Fist0

What is wrong with this code?

medium📝 Debug Q7 of Q15
Python - Context Managers
What is wrong with this code?
class MyContext:
    def __enter__(self):
        print('Start')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Cleanup')

with MyContext():
    print('Inside')
AIndentation error in the with block
BMissing return in __exit__
CNo __init__ method defined
DCannot use with without 'as' keyword
Step-by-Step Solution
Solution:
  1. Step 1: Check indentation of with block

    The print statement inside the with block is not indented, causing a syntax error.
  2. Step 2: Verify other parts

    __exit__ does not require a return, __init__ is optional, and 'as' is optional if no variable needed.
  3. Final Answer:

    Indentation error in the with block -> Option A
  4. Quick Check:

    With block code must be indented [OK]
Quick Trick: Indent code inside with block properly [OK]
Common Mistakes:
MISTAKES
  • Forgetting indentation inside with
  • Thinking __exit__ must return True
  • Assuming 'as' is mandatory

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes