上下文管理器即 with
語句,這是 python 獨有的語句。
with
常用於文件操作,with
語句執行結束後被打開的文件自動關閉,代碼更簡潔:
with open("myfile.txt", 'r') as file:
pass
其中,open
是一個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()
上下文管理器的實現:
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()
數據庫的代碼因此可以簡化:
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