python runtime_error ai_generated true

RecursionError: 调用 Python 对象时超出最大递归深度

RecursionError: maximum recursion depth exceeded while calling a Python object

ID: python/pytest-recursion-error-in-fixture

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-07-03首次发现

版本兼容性

版本状态引入弃用备注
7.x active
8.x active

根因分析

夹具直接或间接依赖自身,导致夹具解析期间无限递归。这通常发生在夹具名称与其请求的参数名称相同时。

English

A fixture directly or indirectly depends on itself, causing infinite recursion during fixture resolution. This often happens when a fixture has the same name as a parameter it requests.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def db_connection():
        return create_connection()
    
    @pytest.fixture
    def db_session(db_connection):  # Different name
        return Session(db_connection)
  2. 85% 成功率
    @pytest.fixture
    def my_fixture(request):
        other = request.getfixturevalue('other_fixture')
        return process(other)

无效尝试

常见但无效的做法:

  1. 90% 失败

    This delays the inevitable crash and may cause a stack overflow, potentially crashing the Python interpreter.

  2. 95% 失败

    RecursionError occurs during fixture resolution, before the fixture body executes. The try/except inside the fixture never catches it.