Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
Johnny Metz Avatar asked May 13 '19 18:05

Johnny Metz


People also ask

What is an engine in SQLAlchemy?

The Engine is the starting point for any SQLAlchemy application. It's “home base” for the actual database and its DBAPI, delivered to the SQLAlchemy application through a connection pool and a Dialect , which describes how to talk to a specific kind of database/DBAPI combination.

How does SQLAlchemy Session work?

In the most general sense, the Session establishes all conversations with the database and represents a “holding zone” for all the objects which you've loaded or associated with it during its lifespan. It provides the interface where SELECT and other queries are made that will return and modify ORM-mapped objects.

What function from the Session object is used to delete items in SQLAlchemy?

delete() is invoked upon an object and the Session is flushed, the row is deleted from the database.

What SQLAlchemy execute return?

SQLAlchemy execute() return ResultProxy as Tuple, not dict.


1 Answers

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
like image 101
Johnny Metz Avatar answered Oct 09 '22 14:10

Johnny Metz