This is an anti-pattern explicitly called out in the SqlAlchemy documents.
### this is the **wrong way to do it** ###
class ThingOne(object):
def go(self):
session = Session()
try:
session.query(FooBar).update({"x": 5})
session.commit()
except:
session.rollback()
raise
class ThingTwo(object):
def go(self):
session = Session()
try:
session.query(Widget).update({"q": 18})
session.commit()
except:
session.rollback()
raise
def run_my_program():
ThingOne().go()
ThingTwo().go()
Also from the docs:
tl;dr;
As a general rule, keep the lifecycle of the session separate and external from functions and objects that access and/or manipulate > database data.