Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittests for mypy reveal_type

I have some points in legacy code (python library: music21) that uses a lot of overloading and Generic variables to show/typecheck that all subelements in a t.Sequence belong to a particular type. There are a lot of @overload decorators to show how different attributes can return different values. At this point the functions work as they should, but a number of PRs in the past have broken the introspection that other devs require.

The code is extensively tested, but the inferred types by checkers such as mypy and PyCharm are not. Is there a way to run testing on inferred types? Something like:

SomeClassType = typing.TypeVar('SomeClassType', bound='SomeClass')

class SomeClass:
    pass

class DerivedClass(SomeClass):
    pass

class MyIter(typing.Sequence[typing.Type[SomeClassType]]):
    def __init__(self, classType: typing.Type[SomeClassType]):
        self.classType = classType

# ------- type_checks.py...
derived_iterator = MyIter(DerivedClass)

# this is the line that I don't know exists...
typing_utilities.assert_reveal_type_eq(derived_iterator, 
                                       MyIter[DerivedClass])
# or as a string 'MyIter[DerivedClass]'

mypy's reveal_type seems like it would be helpful here, but I can't seem to find any integration into a testing system, etc. Thanks!

like image 903
Michael Scott Asato Cuthbert Avatar asked Oct 31 '25 13:10

Michael Scott Asato Cuthbert


1 Answers

The function you are looking for actually exists. But it is called differently:

First, define a type test:

from typing_extensions import assert_type

def function_to_test() -> int:
    pass


# this is a positive test: we want the return type to be int
assert_type(function_to_test(), int)

# this is a negative test: we don't want the return type to be str
assert_type(function_to_test(), str)  # type: ignore

Then run mypy on the file: mypy --strict --warn-unused-ignores.

The positive tests that fail are simply reported as a mypy error and the negative tests that fail are reported as 'Unused "type: Ignore" comment'.

The package typing_extensions is installed alongside mypy.

Source: https://typing.readthedocs.io/en/latest/source/quality.html

like image 69
Wombatz Avatar answered Nov 03 '25 03:11

Wombatz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!