我在遗留代码(python 库:music21)中有一些要点,它使用大量重载和通用变量来显示/类型检查 t.Sequence 中的所有子元素是否属于特定类型。有很多 @overload 装饰器来展示不同的属性如何返回不同的值。此时,功能可以正常工作,但过去的一些 PR 已经打破了其他开发人员所需的内省(introspection)。
代码经过了广泛的测试,但 mypy 和 PyCharm 等检查器推断的类型并未经过测试。有没有办法对推断类型进行测试?像这样的东西:
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 的 reveal_type
似乎在这里会有帮助,但我似乎找不到任何与测试系统的集成等。谢谢!
最佳答案
您正在寻找的功能确实存在。但它的叫法不同:
首先,定义类型测试:
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
然后在文件上运行 mypy:mypy --strict --warn-unused-ignores
。
失败的正面测试仅报告为 mypy 错误,而失败的负面测试则报告为“未使用的“类型:忽略”注释”。
包 typing_extensions
与 mypy 一起安装。
来源:https://typing.readthedocs.io/en/latest/source/quality.html
关于pycharm - mypy Reveal_type 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73329642/