Add Session context manager

Issue #3736 wontfix
Chris Herrick created an issue

It would be very nice if the Session object had a context manager similar to the following:

def __enter__(self):
    return self

def __exit__(self, type, value, traceback):
    self.flush()

Comments (5)

  1. Mike Bayer repo owner

    the usual context manager use w/ Session is:

    with session.transaction:
        # code
    

    that's already there (it needs to be in the documentation though). It does a commit() at the end. flush() is awkward because you should already be using autoflush; calling flush() manually is not very common. Does this suit your use case?

  2. Chris Herrick reporter

    The following approach is still awkward (although very valid).

    session = makesession()
    with session.transaction:
       # code
    

    I would find the following to be more intuitive and useful.

    with sessionmaker() as session:
       # code
    

    This may be personal preference.

  3. Mike Bayer repo owner

    also, does it help that you can subclass Session and make any context managers you want ?

  4. Log in to comment