Skip to content

autospec doesn't work with lazy-imported symbols #153888

Description

@zsol

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.15pre-release feature fixes, bugs and security fixes3.16new features, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytopic-lazy-importstype-bugAn unexpected behavior, bug, or error

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions