It appears that in Python versions 3.12 and earlier, mock_open().__exit__ was always called with 4 args (self, exctype, excinst, exctb) when used with contextlib.ExitStack but that used to be a no-op before the exit handler was added.
I'm not sure whether this should be fixed by:
changing the way ExitStack calls its stack of __exit__ callbacks
making mock_open and open more similar, or
making mock_open's exit handler take *args, **kwargs same as the enter handler??
Activity
Add news entry for pythongh-150484
add news fragment for pythongh-150484 mock_open fix
serhiy-storchaka commented on May 29, 2026
This was fixed in 3.15 (most likely in #144386), so only 3.13 and 3.14 need a fix (too late for 3.12, security bugs only).
Yes, using *args is a correct fix for these versions.
clarker0 commented on Jun 1, 2026
3.12 is working fine! sorry for the confusion, I added it to the "tested on" versions list in order to bisect where the issue came from.
only 3.13 and 3.14 are affected by this issue.
a fix for 3.14 would be hugely appreciated, thanks 😄
[3.14] gh-150484: Fix mock_open __exit__ with contextlib.ExitStack (G…
[3.13] gh-150484: Fix mock_open __exit__ with contextlib.ExitStack (G…