The context manager is with
sentence , This is a python Unique statement .
with
Often used for file operations ,with
After the statement is executed, the opened file is automatically closed , The code is simpler :
with open("myfile.txt", 'r') as file:
pass
among ,open
It's a class.
You can also implement custom Context manager , for example , The following database operation code has many repetitions , Whether it's creating , Update or delete , Connect to the database every time , Close the database , To avoid this repetition , You can write the code to be executed each time to a context manager , That is, in a class .
def get_all_books():
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute("SELECT * FROM books")
books = [{
'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
connection.close()
return books
def add_book(name, author):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))
connection.commit()
connection.close()
Implementation of context manager :
import sqlite3
class DatabaseConnection:
def __init__(self, host):
self.connection = None
self.host = host
def __enter__(self):
self.connection = sqlite3.connect(self.host)
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type or exc_val or exc_tb: # in case of any error, close the connection without commit
self.connection.close()
else:
self.connection.commit()
self.connection.close()
The database code can therefore be simplified :
def add_book(name, author):
with DatabaseConnection('data.db') as connection:
cursor = connection.cursor()
cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))
def get_all_books():
with DatabaseConnection('data.db') as connection:
cursor = connection.cursor()
cursor.execute("SELECT * FROM books")
books = [{
'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
return books