pycharm - mypy Reveal_type 的单元测试

标签 pycharm mypy python-typing

我在遗留代码(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/

相关文章:

docker - 带有 Docker 镜像的 PyCharm 在 RUN 命令上返回 "Process finished with exit code 128"

python - 如何注释函数枚举

python - 字段类型取决于其他字段的类型

django - 在模型中为Django字段指定类型(对于Pylint)

twisted - 升级到 Twisted 21.2.0 时出现 Mypy 输入错误

python - 是时候举手 throw 了吗?

python - 在 PyCharm 中,运行单元测试时如何向 pytest 添加自定义参数?

python - Python 如何知道要使用哪种数字类型来将任意两个数字相乘?

python - Pycharm:如果路径包含空格,运行管理任务将不起作用

python - 返回类的类型声明在 PyCharm 中给出错误