Skip to content
Discussion options

You must be logged in to vote

You can achieve the desired functionality like this:

from sqlmodel import Session as SQLModelSession
from contextlib import contextmanager

engine = ...

@contextmanager
def Session():
    session = SQLModelSession(engine)
    try:
        yield session
    finally:
        session.close()

Then, you can use Session as a context manager without passing the engine every time:

with Session() as session:
    ...

Replies: 12 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by tiangolo
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
8 participants
Converted from issue

This discussion was converted from issue #75 on December 31, 2025 09:12.