9

For example, is there a difference between the following two?

session = Session() # Session is a session maker
try:
    # do some work
    session.commit()
except:
    session.rollback()
finally:
    session.close()

and

session = Session()
try:
    # do some work
    session.commit()
finally:
    session.close()

The latter is what I used to do, because I assumed closing the session before committing (in case of an error) had the same effect as rolling back. But I saw the first form here.

lfk
  • 2,423
  • 6
  • 29
  • 46

1 Answers1

13

Closing a session will implicitly roll back current transactional state:

The close() method issues a expunge_all(), and releases any transactional/connection resources. When connections are returned to the connection pool, transactional state is rolled back as well.

But I'd argue that the first form is still better, since explicit is better than implicit. The author of SQLAlchemy also seems to reflect this sentiment.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
  • Explicit is always better than Implicit :) – Dinesh Pundkar Oct 18 '17 at 06:28
  • 2
    @DineshPundkar Explicit better than implicit should be analysed on a case by case basis. For instance, you might not find it preferable to specify all default arguments of a function every time you use it. Imagine how the print statement would look like if you do that? – adriaanbd Dec 09 '21 at 15:24