9

Sqlalchemy's documentation says that one can create a session in two ways:

from sqlalchemy.orm import Session
session = Session(engine)

or with a sessionmaker

from sqlalchemy.orm import session_maker
Session = session_maker(engine)
session = Session()

Now in either case one needs a global object (either the engine, or the session_maker object). So I do not really see what the point of the session_maker is. Maybe I am misunderstanding something.

I could not find any advice when one should use one or the other. So the question is: In which situation would you want to use Session(engine) and in which situation would you prefer session_maker?

Felix B.
  • 905
  • 9
  • 23

1 Answers1

8

The docs describe the difference very well:

Session is a regular Python class which can be directly instantiated. However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.

rfkortekaas
  • 6,049
  • 2
  • 27
  • 34
  • but if you are in some module, you would have to import the sessionmaker object in order to create a session with it. At this point you might as well import the engine and create a session object with it. I do not quite see the benefit – Felix B. Mar 02 '21 at 11:50
  • I mean is the benefit really only the difference between `Session()` and `Session(engine)`? – Felix B. Mar 02 '21 at 11:52
  • 1
    It's not only the benefit of adding the `engine` object but a lot of other configuration options that you can add to the [session](https://docs.sqlalchemy.org/en/14/orm/session_api.html#sqlalchemy.orm.Session). When you have an extensive configuration you notice the benefit of `sessionmaker`. – rfkortekaas Mar 02 '21 at 12:01