sqlalchemy: Why create a sessionmaker before assign it to a Session object?
orm, python, session, sqlalchemy
Solution
The reason `sessionmaker()` exists is so that the various "configurational" arguments it requires only need to be set up in one place, instead of repeating "bind=engine, autoflush=False, expire_on_commit=False", etc. over and over again. Additionally, `sessionmaker()` provides an "updateable" interface, such that you can set it up somewhere in your application:
session = sessionmaker(expire_on_commit=False)
but then later, when you know what database you're talking to, you can add configuration to it:
session.configure(bind=create_engine("some engine"))
It also serves as a "callable" to pass to the very common `scoped_session()` construct:
session = scoped_session(sessionmaker(bind=engine))
With all of that said, these are just conventions that the documentation refers to so that a consistent "how to use" story is presented. There's no reason you can't use the constructor directly if that is more convenient, and I use the `Session()` constructor all the time. It's just that in a non-trivial application, you will probably end up sticking that constructor call to `Session()` inside some kind of callable function anyway, `sessionmaker()` serves as a default for that callable.
Problem
Why I always need to do that in 2 steps in SqlAlchemy? ``` import sqlalchemy as sa import sqlalchemy.orm as orm engine = sa.create_engine(<dbPath>, echo=True) Session = orm.sessionmaker(bind=engine) my_session = Session() ``` Why I cannot do it in one shot like (it's could be more simple, no?) : ``` import sqlalchemy as sa import sqlalchemy.orm as orm engine = sa.create_engine(<dbPath>, echo=True) Session = orm.Session(bind=engine) ```