with statements open a resource and guarantee that the resource will be closed when the with block completes, regardless of how the block completes. Consider a file:

with open('/etc/passwd', 'r') as f:
    print f.readlines()

print "file is now closed!"

The file is guaranteed to be closed at the end of the block -- even if you have a return, even if you raise an exception.

In order for with to make this guarantee, the expression (open() in the example) must be a context manager. The good news is that many python expressions are context managers, but not all.

According to a tutorial I found, MySQLdb.connect() is, in fact, a context manager.

This code:

conn = MySQLdb.connect(...)
with conn:
    cur = conn.cursor()
    cur.do_this()
    cur.do_that()

will commit or rollback the sequence of commands as a single transaction. This means that you don't have to worry so much about exceptions or other unusual code paths -- the transaction will be dealt with no matter how you leave the code block.

Answer from Robᵩ on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › reference › compound_stmts.html
8. Compound statements — Python 3.15.0 documentation
5 days ago - Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong: ... Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print() calls are executed: ... compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | match_stmt | funcdef | classdef | async_with_stmt | async_for_stmt | async_funcdef suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT statement: stmt_list NEWLINE | compound_stmt stmt_list: simple_stmt (";" simple_stmt)* [";"]
🌐
GeeksforGeeks
geeksforgeeks.org › python › with-statement-in-python
with statement in Python - GeeksforGeeks
It writes "Hello, Python!" to the file, replacing any existing content. The with statement relies on context managers, which manage resource allocation and deallocation using two special ...
Published: July 17, 2026
🌐
Preshing
preshing.com › 20110920 › the-python-with-statement-by-example
The Python "with" Statement by Example
September 20, 2011 - For example, suppose we mistakenly passed the wrong number of arguments to the rectangle call. In that case, the steps taken by the Python interpreter would be: The rectangle method raises a TypeError exception: “Context.rectangle() takes exactly 4 arguments.” · The with statement catches this exception.
🌐
Built In
builtin.com › software-engineering-perspectives › what-is-with-statement-python
What Is the With Statement in Python? | Built In
The with statement in Python simplifies ... and closing files. For example, instead of manually opening and closing resources using a try-finally block, the with statement manages this automatically....
🌐
Real Python
realpython.com › python-with-statement
Python's with Statement: Manage External Resources Safely – Real Python
October 21, 2025 - The threading.Lock class in the Python standard library also supports the with statement. This class provides a primitive lock to prevent multiple threads from modifying a shared resource at the same time in a multithreaded application. You can use a Lock object in a with statement to automatically acquire and release a given lock. For example, say you need to protect the balance of a bank account:
🌐
W3Schools
w3schools.com › python › python_statements.asp
Python Statements
In Python, a statement usually ends when the line ends. You do not need to use a semicolon (;) like in many other programming languages (for example, Java or C).
Top answer
1 of 3
14

with statements open a resource and guarantee that the resource will be closed when the with block completes, regardless of how the block completes. Consider a file:

with open('/etc/passwd', 'r') as f:
    print f.readlines()

print "file is now closed!"

The file is guaranteed to be closed at the end of the block -- even if you have a return, even if you raise an exception.

In order for with to make this guarantee, the expression (open() in the example) must be a context manager. The good news is that many python expressions are context managers, but not all.

According to a tutorial I found, MySQLdb.connect() is, in fact, a context manager.

This code:

conn = MySQLdb.connect(...)
with conn:
    cur = conn.cursor()
    cur.do_this()
    cur.do_that()

will commit or rollback the sequence of commands as a single transaction. This means that you don't have to worry so much about exceptions or other unusual code paths -- the transaction will be dealt with no matter how you leave the code block.

2 of 3
8

Fundamentally it's a object that demarcates a block of code with custom logic that is called on entrance and exit and can take arguments in it's construction. You can define a custom context manager with a class:

class ContextManager(object):

    def __init__(self, args):
        pass

    def __enter__(self):
        # Entrance logic here, called before entry of with block
        pass

    def __exit__(self, exception_type, exception_val, trace):
        # Exit logic here, called at exit of with block
        return True

The entrance then gets passed an instance of the contextmanager class and can reference anything created in the __init__ method (files, sockets, etc). The exit method also receives any exceptions raised in the internal block and the stack trace object or Nones if the logic completed without raising.

We could then use it like so:

with ContextManager(myarg):
    # ... code here ...

This is useful for many things like managing resource lifetimes, freeing file descriptors, managing exceptions and even more complicated uses like building embedded DSLs.

An alternative (but equivalent) method of construction is to the contextlib decorator which uses a generator to separate the entrance and exit logic.

from contextlib import contextmanager

@contextmanager
def ContextManager(args):
    # Entrance logic here
    yield
    # Exit logic here
🌐
Towards Data Science
towardsdatascience.com › home › artificial intelligence › what is behind the python "with" statement?
What Is Behind The Python "with" Statement? | Towards Data Science
June 27, 2022 - The open() function is such an example. That is, we write a with-statement with this function and give the filename that we want to open. Then, it opens the file within this context and the connection is destroyed when leaving the context.
Find elsewhere
🌐
Medium
kaushikshamantha.medium.com › with-in-python-c2ef842ec221
“with” in Python. The with statement is used to ensure… | by Kaushik Shamantha | Medium
March 4, 2024 - It is commonly used with file ... and ensure it's closed properly with open('example.txt', 'r') as file: contents = file.read() print(contents) # File is automatically closed when exiting the 'with' block # No need to use ...
🌐
freeCodeCamp
freecodecamp.org › news › with-open-in-python-with-statement-syntax-example
With Open in Python – With Statement Syntax Example
July 12, 2022 - The Python programming language has various functions and statements for working with a file. The with statement and open() function are two of those statements and functions. In this article, you will learn how to use both the with statement and ope...
🌐
TutorialsPoint
tutorialspoint.com › what-is-the-use-of-the-with-statement-in-python
What is the use of the WITH statement in Python?
September 22, 2022 - Here's how to read a file using the with statement ? # Creating a sample file content content = """Good Morning this is Tutorials Point sample File Consisting of Specific Good source codes in Python,Seaborn,Scala Summary and Explanation""" # Write to file first with open("sample_file.txt", "w") as f: f.write(content) # Read the file using with statement print("The lines of a given Text File are:") with open("sample_file.txt", "r") as file_data: file_lines = file_data.readlines() for text_line in file_lines: print(text_line.strip())
🌐
PYnative
pynative.com › home › python › python statements
Python Statements With Examples– PYnative
September 1, 2021 - Learn Python statements. Create a single and multiline statement. Understand simple and compound statements such as print, Assignment, Conditional, and Looping statements.
🌐
Educative
educative.io › answers › the-with-statement-in-python
The 'with' statement in Python
The with statement in Python is used for resource management and exception handling. You’d most likely find it when working with file streams. For example, the statement ensures that the file stream process doesn’t block other processes if an exception is raised, but terminates properly.
🌐
Python
docs.python.org › 2.5 › whatsnew › pep-343.html
8 PEP 343: The 'with' statement
May 13, 2005 - The contextlib module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don't need to write nested 'with' statements. In this example, the single 'with' statement both starts a database transaction and acquires a thread lock:
🌐
Python
peps.python.org › pep-0343
PEP 343 – The “with” Statement | peps.python.org
The notion of using the PEP 342 generator API directly to define the with statement was also briefly entertained [6], but quickly dismissed as making it too difficult to write non-generator based context managers. The generator based examples rely on PEP 342.
🌐
Luis Llamas
luisllamas.es › home › courses › python programming course
Python with Statement for Resource Management
November 20, 2024 - In this example, open('archivo.txt', 'r') returns a file object that implements the context protocol. The file is opened for reading, and upon exiting the with block, the file is automatically closed, even if an exception occurs within the block. The with statement works with objects known as context managers.
🌐
Analytics Vidhya
analyticsvidhya.com › home › understanding the with statement in python
Understanding the with Statement in Python - Analytics Vidhya
January 15, 2024 - In this snippet, the ‘with’ statement not only opens the ‘example.txt’ file in read mode but also automatically closes it upon block execution, ensuring proper cleanup. Also Read: 3 Easy Ways to Handle Command Line Arguments in Python
🌐
Codingem
codingem.com › home › the with statement in python
with Statement in Python - codingem.com
June 14, 2022 - It ensures no resources are accidentally left open. The with statement is a replacement for commonly used try/finally error-handling statements. A common example of using the with statement is opening a file.
🌐
EyeHunts
tutorial.eyehunts.com › home › python with statement | example code
Python with statement | Example code
May 4, 2022 - Python with statement is used with try/finally statements. It is used with unmanaged resources (like file streams). The with the statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. ... Simple example code using “with statement”.
🌐
Scaler
scaler.com › home › topics › python › with statement in python
with Statement in Python - Scaler Topics
November 22, 2023 - Python's with statement is used for resource management and exception handling. It simplifies the management of shared resources like file streams, ensuring that resources are properly cleaned up after use, regardless of whether an exception is raised. This statement makes the code cleaner and much more readable. Here's a concise example using the with statement for file handling: