Assigning to a target

suggest change

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()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents