I have a bunch of python methods that follow this pattern:
conn = get_conn()
cur = conn.cursor()
cur.execute("delete from sessions where guid=%s", guid)
You could write a context manager and use the with statement. For example, see this blog post:
Also the python documentation has a sample that pretty much matches your needs. See section 8.1 on this page, in particular the snippet that begins:
db_connection = DatabaseConnection() with db_connection as cursor: cursor.execute('insert into ...') cursor.execute('delete from ...') # ... more operations ...