静态类型检查器 Mypy 0.620 发布,支持 Data Classes

综合编程 2018-07-16 阅读原文

Mypy 0.620 已发布,包含一些新特性和 bug 修复。Mypy 是 Python 的可选静态类型检查器,旨在结合动态类型和静态类型的优点。新版本可按如下方式安装:

 python3 -m pip install -U mypy

亮点包括:

支持 Python 3.7 的 data classes

    from dataclasses import dataclass    from typing import List    
    @dataclass
    class FitResult:
        optimum: List[float]
        chi: float
        method: str = "TRF"
    
    FitResult([0.1, 0.2], 1.2)  # OK
    FitResult([0.1, 0.2], 1.2, "LM")  # Also OK
    FitResult(1, 2)  # Error!

泛型类型过载和其他过载改进

    from typing import List, Union, overload    
    @overload
    def summarize(data: List[int]) -> float: ...    @overload
    def summarize(data: List[str]) -> str: ...    def summarize(data):
        # Implementation goes here
        ...
    
    gen_data: Union[List[int], List[str]]
    res = summarize(gen_data)  # OK, inferred type is Union[float, str]
    
    bad_data: int
    summarize(bad_data)    # error: No overload variant of "summarize" matches argument type "int"
    # note: Possible overload variants:
    # note:     def summarize(data: List[int]) -> float
    # note:     def summarize(data: List[str]) -> str

Incomplete and partial packages

    # pack/__init__.pyi
    from typing import Any    def __getattr__(arrr: str) -> Any: ...    
    # pack/subpack/__init__.pyi
    # empty
    
    # pack/subpack/mod.pyi
    class Test: ...    
    # main.py
    from pack import other  # OK, pack is incomplete
    other.func(1, 2)  # OK, all types in incomplete packages are Any
    
    from pack.subpack import mod  # OK
    from pack.subpack import another  # Error: missing library stub file

完整更新内容请查阅:

开源中国

责编内容by:开源中国阅读原文】。感谢您的支持!

您可能感兴趣的

matplotlib: Generating line and pie charts in Pyth... Let’s take a look at how we can generate plots in Python. matplotlib is a pa...
Introducing a simple and intuitive Python API for ... Introducing a simple and intuitive API for UCI machine learning portal, where...
将数据加载到网络 训练一个机器学习深度学习模型一般可以简单概括为以下三个步骤: 准备数据 定义网络结构 训练 我们可以把整个过程用下面的...
15_Python模块化编程_Python编程之路 之前跟大家讲的是一些python的数据基础,从这篇文章开始,我们开始正式学习python的模块化编程 下面我们解释一下什么叫做模块 之前已经讲...
HG659 Router | Python Reboot Code Here is some quick code to allow programmatically rebooting your HG659 router. ...