Search code examples
pythonsqlalchemypython-typingmypy

Type hints for SQLAlchemy engine and session objects


I'm trying to add type hints to my SQLAlchemy script:

connection_string: str = "sqlite:///:memory:"
engine = create_engine(connection_string)
session = Session(bind=engine)
reveal_type(engine)
reveal_type(session)

I've ran this script against mypy but both types comes back as Any. What type should the engine and session variable be?


Solution

  • Figured it out:

    connection_string: str = "sqlite:///:memory:"
    engine = create_engine(connection_string)
    session = Session(bind=engine)
    print(type(engine))   # sqlalchemy.engine.base.Engine
    print(type(session))  # sqlalchemy.orm.session.Session
    

    Thus, type hinting is achieved the following way for example:

    from sqlalchemy.engine.base import Engine
    
    def test_func(engine: Engine):
        pass