You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中DI创建SQLAlchemy会话遇Pylance类型表达式警告如何解决

解决Pylance "Variable not allowed in type expression" 警告

问题原因

SessionLocal是sessionmaker创建的会话工厂实例,并非Python类型系统认可的类型对象,Pylance不允许在类型注解中使用普通变量,因此触发警告。

修复方案

直接使用SQLAlchemy提供的Session类型作为返回注解,步骤如下:

  1. 从sqlalchemy.orm导入Session类型
  2. 将get_session函数的返回类型注解改为Session

修改后的代码:

from sqlalchemy.orm import sessionmaker, Session

SessionLocal = sessionmaker(engine, **sqlalchemy_session_options)

def get_session() -> Session:
    with SessionLocal() as database:
        yield database

关于忽略警告

如果暂时不想调整代码,可以通过添加注释忽略该警告:

def get_session() -> SessionLocal:  # type: ignore[valid-type]
    with SessionLocal() as database:
        yield database

但更推荐使用前一种修复方案,因为它能提供更准确的类型提示,符合Python类型注解的规范。

内容的提问来源于stack exchange,提问作者postcoital-solitaire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 11:43:13