Mypy: Dict arguments that contain a subclass are not handled by Mypy correctly

Created on 19 Nov 2020  路  1Comment  路  Source: python/mypy

I have the following example piece of code

from typing import Any, Dict


class P:
    pass

class C(P):
    pass

class A:
    def __init__(self, x: Dict[P, Any]):
        pass

class B(A):
    def __init__(self, x: Dict[C, Any]):
        super().__init__(x)

When running mypy on it, this warning appears:

Argument 1 to "__init__" of "A" has incompatible type "Dict[C, Any]"; expected "Dict[P, Any]"

Why is this happening? If I do the same, but without using Dict[], ie:

class P:
    pass

class C(P):
    pass

class A:
    def __init__(self, x: P):
        pass

class B(A):
    def __init__(self, x: C):
        super().__init__(x)

I get no complains. I tried using Mapping[] instead of Dict[] but the same warning occurs.

This happens a lot in the code, as I am subclassing from a Library class, I cannot use cast every time, it's counter productive

Environment

  • Mypy version used: 0.790
  • Python version used: 3.8.5
  • Operating system and version: Ubuntu 20.04
bug

Most helpful comment

Duplicate of https://github.com/python/typing/issues/445 and https://github.com/python/mypy/issues/1114 (see also https://github.com/python/typing/pull/273#issuecomment-243864718)

>All comments

Duplicate of https://github.com/python/typing/issues/445 and https://github.com/python/mypy/issues/1114 (see also https://github.com/python/typing/pull/273#issuecomment-243864718)

Was this page helpful?
0 / 5 - 0 ratings