Why is mypy complaning about direct subclasses of the expected Type?

Viewed 190

I have looked in both Mypy's docs as well as python's docs as well and I still don't quite understand what is wrong here

from typing import NewType
from numbers import Number


def foo(num: Number):
    print(num)

foo(5)

A = NewType("A", str)
B = NewType("B", A)

test_var_1 = A("test")
test_var_2 = B(A("test"))
test_var_3 = B("test")
mypytest.py:8: error: Argument 1 to "foo" has incompatible type "int"; expected "Number"
mypytest.py:15: error: Argument 1 to "B" has incompatible type "str"; expected "A"

According to the answers from this question mypy shouldn't be complaining about foo, isn't the whole point of classes like numbers.Number or collections.abc.Sequence among other abstract classes that you cant hint that any subclass of those are acceptable parameter to a function? (Along with serving for user defined subclasses).

Moreover, with regards to the NewType "subclassing", python has an example of this right from the docs:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

Mypy Version: 0.910

Python Version: 3.9.7

EDIT: Mypy suggests that NewType is equivalent to creating an empty subclass but with less runtime overhead, however the same example from above using classes passes with no issues:

class A(str):
    pass

class B(A):
    pass


test_var_1 = A("test")
test_var_2 = B(A("test"))
test_var_3 = B("test")
Success: no issues found in 1 source file
0 Answers
Related