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

basedpyright报错:函数/方法内装饰函数提示‘未被访问’问题咨询

问题背景

示例使用的quart-trio包,接口和功能与flask类似。

无报错的全局作用域代码

from quart_trio import QuartTrio

app = QuartTrio(__name__)

@app.route('/')
async def index() -> str:
    return "ok"

app.run()

触发报错的函数封装代码

逻辑和上面一致,但basedpyright会抛出reportUnusedFunction错误:

from quart_trio import QuartTrio

def create_app() -> QuartTrio:
    app = QuartTrio(__name__)

    @app.route('/')
    async def index() -> str:           # error: Function "index" is not accessed (reportUnusedFunction)
        return "ok"

    return app

app = create_app()
app.run()

触发报错的类封装代码

类方法内同样会触发相同的未使用函数错误:

from quart_trio import QuartTrio

class Server:
    def __init__(self) -> None:
        super().__init__()
        self.app = QuartTrio(__name__)

        @self.app.route('/')
        async def index() -> str:       # error: Function "index" is not accessed (reportUnusedFunction)
            return "ok"

    def serve(self) -> None:
        self.app.run()

Server().serve()

疑问

  • 为何会出现该报错?
  • 有无更优写法避免触发检查?
  • 这是否属于basedpyright的bug需提交?

解答

报错原因

basedpyright的静态分析逻辑在**局部作用域(函数/类方法内部)**无法识别@app.route装饰器对被装饰函数的隐式调用。在全局作用域时,分析器能关联到框架的路由注册逻辑,但当装饰器出现在函数或类方法内部时,静态分析没法追踪到index函数已经被装饰器注册到app实例中,因此误判这个函数没被使用。

避免报错的写法

有几种实用的解决方式:

  • 添加类型忽略注释:直接跳过该函数的未使用检查,简单直接:
    @app.route('/')
    async def index() -> str:  # type: ignore[unused-function]
        return "ok"
    
  • 显式调用装饰器:把函数定义和装饰器调用分开,让分析器能感知到函数被使用:
    async def index() -> str:
        return "ok"
    app.route('/')(index)
    
  • 使用匿名lambda(适合简单视图):绕开局部命名的函数,比如:
    app.route('/')(async lambda: "ok")
    
  • 局部配置检查规则:在项目的pyrightconfig.json中针对特定文件或目录关闭该检查(不推荐全局关闭):
    {
      "exclude": [],
      "overrides": [
        {
          "include": ["your_file.py"],
          "reportUnusedFunction": false
        }
      ]
    }
    

是否属于bug

这属于静态分析工具的局限性,而非严格意义上的bug。basedpyright对框架装饰器的识别依赖完善的类型提示或内置规则,如果quart-trio的类型定义没有明确标注route装饰器会保留并使用被装饰的函数,或者basedpyright的分析逻辑没覆盖局部作用域的装饰器场景,就会出现这种误判。

你可以向basedpyright提交反馈,说明局部作用域中使用框架路由装饰器时的误判问题,帮助优化分析逻辑;也可以建议quart-trio完善类型提示,让静态分析工具能正确识别装饰器的行为。


内容的提问来源于stack exchange,提问作者Amadan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:43:29