Python Language Context Managers (“with” Statement) Assigning to a target

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Many context managers return an object when entered. You can assign that object to a new name in the with statement.

For example, using a database connection in a with statement could give you a cursor object:

with database_connection as cursor:
    cursor.execute(sql_query)

File objects return themselves, this makes it possible to both open the file object and use it as a context manager in one expression:

with open(filename) as open_file:
    file_contents = open_file.read()


Got any Python Language Question?