pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

`infer` adds a runtime import of a stub-only name (`unittest.mock._patch_pass_arg`), breaking the module

Open mollydoo opened this issue 1 month ago • 1 comments

pyrefly 1.4.0

from unittest import mock

def patched():
    return mock.patch("os.getcwd")

After pyrefly infer repro.py:

from unittest.mock import _patch_pass_arg
from unittest.mock import MagicMock
from unittest.mock import AsyncMock
from unittest import mock

def patched() -> _patch_pass_arg[AsyncMock | MagicMock]:
    return mock.patch("os.getcwd")

Importing the file now raises:

ImportError: cannot import name '_patch_pass_arg' from 'unittest.mock'

_patch_pass_arg exists only in typeshed's stub for unittest.mock, not in the runtime module, so the inferred annotation breaks a module that imported fine before.

Expected: no runtime import of a stub-only name. For example, the import under if TYPE_CHECKING: with the annotation quoted, or no annotation for that function.

Reproduced with Python 3.14; 1.2.0 behaves the same. Related: #578.

mollydoo avatar Oct 16 '26 14:10 mollydoo

_patch_pass_arg is marked as @type_check_only: https://github.com/python/typeshed/blob/dc4eed3c72ad447baae6ef5a73ac846b1c827e2a/stdlib/unittest/mock.pyi#L290. I guess we can use that to determine when to avoid a runtime import.

rchen152 avatar Nov 05 '26 01:11 rchen152