Mypy is flagging an issue with my code that is really confusing to me. Here’s a snippet of code that illustrates the issue. Note that this is running in Python 3.12.3 and mypy 1.10.0
class A:
pass
class B(A):
pass
def func_of_a(var1: A) -> None:
pass
def func_of_set_of_a(var1: set[A]) -> None:
pass
a = A()
b = B()
b1: B = B()
func_of_a(b1) # mypy does not flag this as being an issue (as expected)
set_of_a: set[A] = {a}
set_of_b: set[B] = {b}
func_of_set_of_a(set_of_a) # mypy does not flag this as being an issue (as expected)
func_of_set_of_a(set_of_b) # mypy flags this as an issue
mypy is flagging func_of_set_of_a(set_of_b)
as being problematic with the following error:
error: Argument 1 to “func_of_set_of_a” has incompatible type “set[B]”; expected “set[A]” [arg-type]
I don’t understand why this is being flagged. func_of_a
expects an object of type A
and will also accept an object of any child class of A
. Shouldn’t func_of_set_of_a
behave similarly? func_of_set_of_a
expects a set[A]
, but shouldn’t it also accept a set of objects of a child class of A? I know I can change the type hint to set[A] | set[B]
, but that would make my code unwieldy since in my actual use case, class A
has many child classes.
What am I missing here?
I tried googling but could not find any info on this. Unless I’m missing it, the official Python documentation also does not address this.
sampf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.