@contextlib.contextmanager
def autonested_transaction(sess):
 if sess.is_active:
  session_context = sess.begin(nested=True)
 else:
  session_context = sess.begin(subtransactions=True)
 with session_context as tx:
  (yield tx)

@ contextlib . contextmanager def autonested_transaction ( sess ) : if sess . is_active : session_context = sess . begin ( nested = True ) else : session_context = sess . begin ( subtransactions = True ) with session_context as tx : ( yield tx )
this is a convenience method to not bother with nested parameter .