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


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:

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 =