Mypy type unification when inheriting from dict

Viewed 53

I would expect the following code to typecheck, but it does not.

from typing import Iterator, Type

class Parent(dict):
    pass

class A(Parent):
    pass

class B(Parent):
    pass

x: Iterator[Type[Parent]] = (A, B).__iter__()

# error: Incompatible types in assignment (expression has type "Iterator[ABCMeta]", variable has type "Iterator[Type[Parent]]"

If I change the parent class to

class Parent():
    pass

It works just fine.

Is there a better way for me to get mypy to see x as a value of type Iterator[Type[Parent]] when Parent inherits from dict?

1 Answers

doing it on two lines works

_x: tuple[type[Parent], type[Parent]] = (A, B)
x: Iterator[type[Parent]] = _x.__iter__()

I guess mypy's a little overeager somewhere

Related