Skip to content

Type hints for __new__ no longer work when subclassing Dict #15135

Closed
@ShaneHarvey

Description

@ShaneHarvey

Bug Report

mypy 1.1.1 introduces a new false positive on pymongo's codebase first noticed in python/typeshed#9694 (comment)

Type hints for __new__ no longer work when subclassing Dict (or dict).

To Reproduce

I see the same behavior on 1.2 and latest:

$ cat repro.py 
from typing import Dict, Any, Type, TypeVar

_Key = TypeVar("_Key")
_Value = TypeVar("_Value")


class MyDict(Dict[_Key, _Value]):
    def __new__(cls: "Type[MyDict[_Key, _Value]]", *args: Any, **kwargs: Any) -> "MyDict[_Key, _Value]":
        return super().__new__(cls, *args, **kwargs)

Error:

$ mypy --strict repro.py           
repro.py:9: error: Value of type variable "Self" of "__new__" of "dict" cannot be "MyDict[_Key, _Value]"  [type-var]
Found 1 error in 1 file (checked 1 source file)

Current workaround is to add # type: ignore[type-var].

Your Environment

  • Mypy version used: 1.1.1, 1.2.0, 1.4.0+dev.bd6ce237f62366f156f4af074e398d761fb41359
  • Mypy command-line flags: --strict although I'm not sure it's needed.
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11.1

Note that in the real code, __new__ is needed to support pickle.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions