{"id":"ea0c21a54548e9d0","repo":"pytest-dev/pytest","slug":"cannot-enter-self-r-twice","errorCode":null,"errorMessage":"Cannot enter {self!r} twice","messagePattern":"Cannot enter (.+?) twice","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/recwarn.py","lineNumber":239,"sourceCode":"                best_idx is None\n                or not issubclass(w.category, self._list[best_idx].category)\n            ):\n                best_idx = i\n        if best_idx is not None:\n            return self._list.pop(best_idx)\n        __tracebackhide__ = True\n        raise AssertionError(f\"{cls!r} not found in warning list\")\n\n    def clear(self) -> None:\n        \"\"\"Clear the list of recorded warnings.\"\"\"\n        self._list[:] = []\n\n    # Type ignored because we basically want the `catch_warnings` generic type\n    # parameter to be ourselves but that is not possible(?).\n    def __enter__(self) -> Self:  # type: ignore[override]\n        if self._entered:\n            __tracebackhide__ = True\n            raise RuntimeError(f\"Cannot enter {self!r} twice\")\n        _list = super().__enter__()\n        # record=True means it's None.\n        assert _list is not None\n        self._list = _list\n        warnings.simplefilter(\"always\")\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        if not self._entered:\n            __tracebackhide__ = True\n            raise RuntimeError(f\"Cannot exit {self!r} without entering first\")\n\n        super().__exit__(exc_type, exc_val, exc_tb)","sourceCodeStart":221,"sourceCodeEnd":257,"githubUrl":"https://github.com/pytest-dev/pytest/blob/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/recwarn.py#L221-L257","documentation":"WarningsRecorder is a non-reentrant context manager; calling __enter__ on an instance that is already entered raises RuntimeError. You must exit before re-entering.","triggerScenarios":"Entering the same WarningsRecorder instance twice without an intervening exit — e.g. two nested `with recwarn:` blocks on the same fixture instance, or a manual __enter__ after the fixture already entered. Hits recwarn.py:239.","commonSituations":"Reusing a session/function-scoped recorder fixture across nested with-blocks; manual context-manager misuse; a helper that enters the recorder the caller also entered.","solutions":["Use a fresh WarningsRecorder instance for each independent with-block.","Ensure __exit__ completes before re-entering the same instance.","Prefer letting the recwarn fixture manage enter/exit; do not enter it manually inside the test."],"exampleFix":"// before\nwith recwarn:\n    ...\nwith recwarn:  # same instance, RuntimeError\n    ...\n// after\nwith WarningsRecorder(_ispytest=True) as w1:\n    ...\nwith WarningsRecorder(_ispytest=True) as w2:\n    ...","handlingStrategy":"validation","validationCode":"if getattr(recorder, '_entered', False):\n    raise RuntimeError('recorder already entered; exit first or use a new instance')\nrecorder.__enter__()","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use a fresh WarningsRecorder per with-block; do not reuse one instance across nested blocks.","Let the recwarn fixture manage enter/exit; avoid manual __enter__ inside tests.","Never nest two `with` blocks on the same recorder instance."],"tags":["pytest","warns","context-manager","runtime"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}