Skip to content

[1.16] Regression in inferring type via unittest.mock.Mock #19184

Closed

Description

@Dreamsorcerer

Bug Report

Regression on type inference found in aiohttp:master.

Seems like the regression may be related to inheriting from Any (which mypy complains about, but is done in typeshed regardless, and has been for many years).

To Reproduce

This is a fairly minimal reproducer of the issue:

from typing import Any, Generic, Protocol, TypeVar
#from unittest.mock import Mock

_T = TypeVar("_T", covariant=True)

class Mock(Any):
    def __init__(self, **kwargs: Any) -> None: ...
    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...


class _Factory(Protocol[_T]):
    def __call__(self, **kwargs: Any) -> _T: ...


class TraceConfig(Generic[_T]):
    def __init__(self, trace_config_ctx_factory: _Factory[_T]) -> None:
        ...

t = TraceConfig(Mock(return_value="foo"))

1.15 Behavior

(First error disappears if we actually import Mock.)

test.py:6: error: Class cannot subclass "Any" (has type "Any")  [misc]
Found 1 error in 1 file (checked 1 source file)

1.16 Behavior

test.py:6: error: Class cannot subclass "Any" (has type "Any")  [misc]
test.py:19: error: Need type annotation for "t"  [var-annotated]
Found 2 errors in 1 file (checked 1 source file)

Activity

  1. ilevkivskyi commented on May 31, 2025

    @ilevkivskyi
    Member

    Hm, if subclassing Any is important here, I think there is a chance this is related to #8829 (on which I am going to work soon).

  2. ilevkivskyi commented on May 31, 2025

    @ilevkivskyi
    Member

    Actually it looks like it was caused by #18587 because we consider that a class with fallback to any may be a metaclass. Maybe we can not do this here, since that special case was added specifically to ignore spurious Anys from type.__call__() IIRC. I will play with this.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-inferenceWhen to infer types or require explicit annotationstopic-protocols

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions