{"record":{"id":"f259d6927b55a572","repo":"RustPython/RustPython","slug":"cannot-enter-r-twice","errorCode":null,"errorMessage":"Cannot enter %r twice","messagePattern":"Cannot enter %r twice","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"Lib/_py_warnings.py","lineNumber":641,"sourceCode":"        self._module = sys.modules['warnings'] if module is None else module\n        self._entered = False\n        if action is None:\n            self._filter = None\n        else:\n            self._filter = (action, category, lineno, append)\n\n    def __repr__(self):\n        args = []\n        if self._record:\n            args.append(\"record=True\")\n        if self._module is not sys.modules['warnings']:\n            args.append(\"module=%r\" % self._module)\n        name = type(self).__name__\n        return \"%s(%s)\" % (name, \", \".join(args))\n\n    def __enter__(self):\n        if self._entered:\n            raise RuntimeError(\"Cannot enter %r twice\" % self)\n        self._entered = True\n        with _wm._lock:\n            if _use_context:\n                self._saved_context, context = self._module._new_context()\n            else:\n                context = None\n                self._filters = self._module.filters\n                self._module.filters = self._filters[:]\n                self._showwarning = self._module.showwarning\n                self._showwarnmsg_impl = self._module._showwarnmsg_impl\n            self._module._filters_mutated_lock_held()\n            if self._record:\n                if _use_context:\n                    context.log = log = []\n                else:\n                    log = []\n                    self._module._showwarnmsg_impl = log.append\n                    # Reset showwarning() to the default implementation to make sure","sourceCodeStart":623,"sourceCodeEnd":659,"githubUrl":"https://github.com/RustPython/RustPython/blob/aaeab4f754b4f40efc0c8ab39cf7c4a3c35a8cfd/Lib/_py_warnings.py#L623-L659","documentation":"warnings.catch_warnings is a one-shot context manager: __enter__ sets an internal _entered flag and raises RuntimeError if the same instance is entered again. Entering twice would save the already-swapped filter state as the 'original', making restoration impossible, so reuse is rejected outright.","triggerScenarios":"cm = warnings.catch_warnings(); with cm: ... followed later by with cm: ... -- reusing a stored instance; a module-level catch_warnings object entered by two different tests.","commonSituations":"Test suites that create the context manager once in a fixture and enter it per test; refactoring a with-block into a helper that receives the cm object; sharing one cm across setup/teardown.","solutions":["Construct a fresh warnings.catch_warnings() for each with statement","In test fixtures, create the instance inside the test or per-test setup, never once at module import","Wrap creation in a small factory function if you need repeated enter/exit cycles"],"exampleFix":"# before\ncm = warnings.catch_warnings()\nwith cm:\n    ...\nwith cm:  # RuntimeError: Cannot enter ... twice\n    ...\n\n# after\nwith warnings.catch_warnings():\n    ...\nwith warnings.catch_warnings():\n    ...","handlingStrategy":"validation","validationCode":"if getattr(cm, \"_entered\", False):\n    cm = warnings.catch_warnings()  # previous use exhausted it; start fresh\nwith cm:\n    ...","typeGuard":"def is_fresh_catch_warnings(cm) -> bool:\n    return not getattr(cm, \"_entered\", False)","tryCatchPattern":"try:\n    with cm:\n        ...\nexcept RuntimeError as e:\n    if \"Cannot enter\" in str(e):\n        with warnings.catch_warnings():\n            ...\n    else:\n        raise","preventionTips":["Construct catch_warnings inline in the with statement; treat instances as single-use","Never share one catch_warnings instance across tests, fixtures, or threads","Nesting distinct instances is fine; re-entering the same one is not"],"tags":["warnings","catch-warnings","runtimeerror","context-manager","reuse"],"backgroundTag":"context-manager-reuse","analyzedSha":"aaeab4f754b4f40efc0c8ab39cf7c4a3c35a8cfd","analyzedAt":"2026-08-17T00:37:52.100Z","schemaVersion":2},"datasetVersion":"2026-08-17T04:17:16.089Z"}