100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

with Statement (Context Managers) in Python

Learn how the 'with' statement uses the context manager protocol (__enter__/__exit__) to guarantee cleanup, such as automatically closing files.

Modules, Files & IterablesIntermediate9 min readJul 7, 2026
Analogies

1. Introduction

The 'with' statement provides a clean, reliable way to acquire and release resources, such as files, locks, or network connections. It is built on top of the context manager protocol, ensuring that cleanup code runs automatically even if an exception occurs inside the block.

🏏

Cricket analogy: Renting a stadium's floodlights for a night match guarantees they're switched off after the game ends, even if the match is abandoned due to rain — just as Python's 'with' statement guarantees cleanup even if an exception occurs.

Using 'with open(...) as f' is the idiomatic way to work with files in Python, because it guarantees the file is closed as soon as the block exits, regardless of how it exits.

🏏

Cricket analogy: Checking out a scorebook from the pavilion 'with' a signed borrowing slip guarantees it's returned to the shelf when you're done, whether you finish the innings notes or get called away — just like 'with open(...) as f' guarantees the file closes.

2. Syntax

python
# Basic file usage
with open('example.txt', 'r') as f:
    data = f.read()
# f is automatically closed here

# Multiple context managers
with open('in.txt') as fin, open('out.txt', 'w') as fout:
    fout.write(fin.read())

# Custom context manager class
class MyContext:
    def __enter__(self):
        # setup code, return value bound to 'as'
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # cleanup code, runs even if an exception occurred
        return False  # False re-raises any exception

3. Explanation

When Python enters a 'with' block, it calls the object's __enter__() method, and the value it returns is bound to the variable after 'as'. When the block finishes, whether normally or due to an exception, Python always calls __exit__(), which is where cleanup (like closing a file) happens.

🏏

Cricket analogy: Entering the dressing room triggers a kit manager to hand you your gear bag (like __enter__ returning a value bound to 'as'), and leaving triggers them to collect and lock it away again (like __exit__), whether you had a good innings or got out for a duck.

This __enter__/__exit__ pair is called the context manager protocol. File objects implement it so that 'with open(...) as f' automatically calls f.close() when the block ends, removing the need to manually manage try/finally blocks.

🏏

Cricket analogy: The pavilion's check-in/check-out system for kit is a protocol every player follows automatically, so no one needs a manual 'remember to return the bat' reminder — just as file objects implement __enter__/__exit__ so 'with open()' auto-closes without a try/finally.

The context manager protocol (__enter__ and __exit__) is what powers the 'with' statement. If __exit__ returns a truthy value, any exception raised inside the block is suppressed; returning False (or None) lets the exception propagate normally.

4. Example

python
import tempfile, os

class Timer:
    def __enter__(self):
        print('Entering context')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exiting context')
        return False

path = os.path.join(tempfile.gettempdir(), 'demo_with.txt')

with open(path, 'w') as f:
    f.write('Managed automatically')

with Timer() as t:
    print('Inside the with block')

with open(path, 'r') as f:
    print(f.read())

os.remove(path)

5. Output

text
Entering context
Inside the with block
Exiting context
Managed automatically

6. Key Takeaways

  • 'with' automatically manages setup and cleanup via the context manager protocol.
  • __enter__() runs at the start of the block; its return value is bound by 'as'.
  • __exit__() always runs at the end of the block, even if an exception was raised.
  • 'with open(...) as f' guarantees the file is closed without an explicit close() call.
  • Multiple context managers can be combined in a single 'with' statement separated by commas.

Practice what you learned

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#WithStatementContextManagersInPython#Statement#Context#Managers#Syntax#StudyNotes#SkillVeris