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

如何正确从pytest导入RaisesContext以用于类型提示?

关于pytest RaisesContext类型提示的正确导入方式
  • 直接导入_pytest.python_api.RaisesContext的可行性:不推荐。以下划线开头的模块属于pytest的内部实现,官方未承诺向后兼容性,后续版本更新可能修改模块结构、类名甚至移除该类,导致代码失效。

  • 正确的显式导入方式(保证类型提示明确且合规):

    1. 延迟导入(字符串字面量)
      无需直接引用内部类,通过字符串类型提示避免运行时依赖,Python 3.7+可结合from __future__ import annotations简化写法:

      from __future__ import annotations
      from typing import Optional
      
      def my_helper(
          should_exit: Optional[RaisesContext] = None,
      ):
          # do stuff
      

      低版本Python可直接用引号包裹类型名:

      from typing import Optional
      
      def my_helper(
          should_exit: Optional["RaisesContext"] = None,
      ):
          # do stuff
      
    2. 基于公共API的类型别名(推荐)
      通过type()获取pytest.raises()返回值的类型,完全依赖pytest公共API:

      from typing import Optional
      import pytest
      
      RaisesContext = type(pytest.raises(Exception))
      
      def my_helper(
          should_exit: Optional[RaisesContext] = None,
      ):
          # do stuff
      

      这种方式既保证类型提示准确,又不会耦合内部实现,mypy等类型检查工具也能正确识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:25:11