From my understanding the only real benefit of using a sessionmaker
is to centrally configure how Session
objects are created.
From the SQLAlchemy docs (emphasis mine):
When do I make a sessionmaker?
Just one time, somewhere in your application’s global scope. It should be looked upon as part of your application’s configuration. If your application has three .py files in a package, you could, for example, place the sessionmaker line in your init.py file; from that point on your other modules say “from mypackage import Session”. That way, everyone else just uses Session(), and the configuration of that session is controlled by that central point.
Also this example in the docs seems to indicate that the purpose of the sessionmaker
is so we can create Session
objects without passing it any configuration arguments.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine(...)
Session = sessionmaker(engine)
# we can now construct a Session() without needing to pass the
# engine each time
with Session() as session:
...
Isn’t all this basically just a fancy specialized functools.partial
? I could achieve the exact same behaviour with partial
(or even just with a function)
With functools.partial
from sqlalchemy import create_engine
from sqlalchemy.orm import Session as _Session
from functools import partial
engine = create_engine(...)
Session = partial(_Session, engine)
with Session() as session:
...
With a function
from sqlalchemy import create_engine
from sqlalchemy.orm import Session as _Session
engine = create_engine(...)
def Session():
return _Session(engine)
with Session() as session:
...
Are there significant additional benefits provided by the sessionmaker
that I’m not aware of?