python / python/cpython

mock.mock_open __exit__ called as instance method from contextlib.ExitStack context

Open
#150,484 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

3.13 3.14 stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

In Python 3.13 onwards:

from contextlib import ExitStack
from unittest import mock
with mock.patch("__main__.open", mock.mock_open()) as m:
    with ExitStack() as exit_stack:
        with exit_stack.enter_context(open("/tmp/test.txt", "w")):
            pass

raises

TypeError: mock_open.<locals>._exit_side_effect() takes 3 positional arguments but 4 were given

The issue seems to come from https://github.com/python/cpython/commit/3f7c0810f6158a7ff37be432f8d7f9511427489f

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:

  1. changing the way ExitStack calls its stack of __exit__ callbacks
  2. making mock_open and open more similar, or
  3. making mock_open's exit handler take *args, **kwargs same as the enter handler??

Thanks

CPython versions tested on:

3.12, 3.13, 3.14

Operating systems tested on:

Linux

Linked PRs
  • gh-150521
  • gh-150535
  • gh-151829
  • gh-151861

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Begin with the reproducer using contextlib.ExitStack and unittest.mock.mock_open, then inspect the callback behavior described in the issue. Done means resolving the Python 3.13+ TypeError while preserving the expected context-manager behavior and adding coverage for the reported case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.