相关疑难解决方法(0)

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

我正在尝试向我的 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变量应该是什么类型?

python sqlalchemy type-hinting mypy

13
推荐指数
1
解决办法
4929
查看次数

稀有对象的 python 类型注释,例如 psycopg2 对象

我了解内置类型。但是我如何指定稀有对象,例如数据库连接对象?

def get_connection_and_cursor() -> tuple[psycopg2.extensions.cursor, psycopg2.extensions.connection]:
    connection = psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host='127.0.0.1', port="5432")
    # connection.autocommit = True
    cursor = connection.cursor()
    return connection, cursor
Run Code Online (Sandbox Code Playgroud)

检查类型,以下是输出:

  • type(cursor)psycopg2.extensions.cursor
  • type(connection)psycopg2.extensions.connection: 。

我应该用它做什么?

python types annotations python-typing

7
推荐指数
1
解决办法
5904
查看次数