Skip to content

gh-150484: Fix mock_open __exit__ with contextlib.ExitStack#150521

Open
factnn wants to merge 2 commits into
python:mainfrom
factnn:fix/mock-open-exit-signature
Open

gh-150484: Fix mock_open __exit__ with contextlib.ExitStack#150521
factnn wants to merge 2 commits into
python:mainfrom
factnn:fix/mock-open-exit-signature

Conversation

@factnn
Copy link
Copy Markdown

@factnn factnn commented May 27, 2026

Summary

Fixes gh-150484: mock_open()'s __exit__ raises TypeError when used with contextlib.ExitStack.

Root cause: _exit_side_effect had a fixed 3-arg signature (exctype, excinst, exctb), but ExitStack.__exit__ calls the managed context's __exit__ with 4 args (self, exctype, excinst, exctb). The mock's side_effect mechanism forwards all args, causing the mismatch.

Fix: Change _exit_side_effect(exctype, excinst, exctb) to _exit_side_effect(*args). The function body only calls handle.close() and doesn't use the arguments.

Changes

  • Lib/unittest/mock.py: 1-line signature fix
  • Lib/test/test_unittest/testmock/testmock.py: regression test

AI Assistance

This PR was developed with AI assistance (Claude). All changed lines have been reviewed by the human submitter.

  mock_open's _exit_side_effect had a fixed 3-arg signature, but
  contextlib.ExitStack calls __exit__ with 4 args (self + 3 exc info).
  Use *args to accept any number of arguments.

  Fixes python#150484
@factnn factnn requested a review from cjw296 as a code owner May 27, 2026 16:18
@bedevere-app
Copy link
Copy Markdown

bedevere-app Bot commented May 27, 2026

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@python-cla-bot
Copy link
Copy Markdown

python-cla-bot Bot commented May 27, 2026

All commit authors signed the Contributor License Agreement.

CLA signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant