Python has something similar to Prolog’s setup_call_cleanup/3, namely “context managers”. One common usage is to open a file and have it automatically closed when not needed, e.g.:
with open("some file", "r") as infile, open("copy of some file", "w") as outfile:
for line in file:
outfile.write(line)
but something similar could be done for queries, so that everything gets cleaned up properly.
For more details, see the with statement, context managers, and contextlib.