SQLAlchemy 引擎和会话对象的类型提示

Joh*_*etz 13 python sqlalchemy type-hinting mypy

我正在尝试向我的 SQLAlchemy 脚本添加类型提示:

connection_string: str = "sqlite:///:memory:"
engine = create_engine(connection_string)
session = Session(bind=engine)
reveal_type(engine)
reveal_type(session)
Run Code Online (Sandbox Code Playgroud)

我已经运行了这个脚本,mypy但两种类型都作为Any. enginesession变量应该是什么类型?

Joh*_*etz 22

弄清楚了:

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
Run Code Online (Sandbox Code Playgroud)

  • 感谢您展示用于解决问题的方法。值得Python新手参考 (2认同)