python / python/cpython

`autospec` doesn't work with lazy-imported symbols

Open
#153,888 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

3.15 3.16 stdlib topic-lazy-imports type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

unittest.mock.patch(target, autospec=True) reads unresolved lazy-import bindings directly from target.__dict__ and autospecs the LazyImportType proxy instead of the imported symbol.

from unittest.mock import patch

lazy from json import dumps

with patch("__main__.dumps", autospec=True) as mock_dumps:
    mock_dumps({})

On CPython main (9d231cbc937f as of now), this raises:

TypeError: 'NonCallableMagicMock' object is not callable

Resolving dumps before patching works. This also affects patch.object, spec=True, and spec_set=True.

A practical example is concurrent.futures.ThreadPoolExecutor, which now uses an explicit lazy import: existing tests such as this one patch it with autospec=True and encounter the same issue.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux, macOS, Windows

Linked PRs
  • gh-153977
  • gh-157768

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

Start with the unittest.mock.patch and patch.object entry points and reproduce the example using a lazy import of json.dumps. Compare autospec=True with spec=True and spec_set=True, including the ThreadPoolExecutor test case linked in the report; done means these cases handle the imported symbol without the reported NonCallableMagicMock error.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.