@__blackjack__: was man als "Kontext" empfindet, ist halt unterschiedlich. Datenbankverbindungen sind etwas anderes als geöffnete Dateien.
Eine Datenbank wird einmal geöffnet und dann macht man verschiedene Transaktionen.
Ein der Kontext hier ist eine Transaktion, also etwas, das man mit commit abschließt.
Code: Alles auswählen
def transaction(connection):
try:
cursor = connection.cursor()
try:
cursor.execute("INSERT INTO …")
finally:
cursor.close()
except:
connection.rollback()
raise
else:
connection.commit()
Und das vereinfacht der Kontextmanager von sqlite3:
Code: Alles auswählen
def transaction(connection):
with connection:
cursor = connection.cursor()
try:
cursor.execute("INSERT INTO …")
finally:
cursor.close()
Ich hätte es sinnvoller gefunden, wenn der Kontextmanager so ausgesehen hätte:
Code: Alles auswählen
class Transaction:
def __init__(self, connection):
self.connection = connection
self.cursor = None
def __enter__(self):
self.cursor = self.connection.cursor()
return self.cursor
def __exit__(self, type, value, traceback):
self.cursor.close()
if type is None:
self.connection.commit()
else:
self.connection.rollback()
with Transaction(connection) as cursor:
cursor.execute("INSERT INTO …")