zoukankan      html  css  js  c++  java
  • Python静态类型

    Mypy是Python的可选静态类型检查器。您可以在Python程序中添加类型提示(PEP 484),并使用mypy进行静态类型检查。查找程序中的错误,甚至不运行它们!

    安装Mypy

    Mypy需要运行Python 3.5或更高版本。下面代码是用的Python 3.7 使用pip安装mypy:

    $ python3 -m pip install mypy

    看几个简单例子:
    平时我们代码大概都是下面的样子:

    # 参数name的类型是未知的
    # 返回的类型也是未知的
    def greeting(name):
        return 'Hello ' + name

    稍微修改一些

    # 参数name后面跟了:str 代表name期望是str类型
    # 参数括号后面跟了->str代表返回类型为str类型
    def greeting(name: str) -> str:
        return 'Hello ' + name
    x: str = 'xxx' # 声明一个变量为str类型
    greeting(x) # Hello xxx
    greeting(123) # TypeError: can only concatenate str (not "int") to str

    到目前为止仅有str、float等基本类型,使用list、tuple复杂类型需要引用typing中的类

    LIST

    数组类型

    from typing import List
    
    # 参数names为list类型并且元素都是str类型
    # 返回为None
    def greet_all(names: List[str]) -> None:
        for name in names:
            print('Hello ' + name)
    
    names = ["Alice", "Bob", "Charlie"]
    ages = [10, 20, 30]
    
    greet_all(names)   # Ok!
    greet_all(ages)    #出错了 Error due to incompatible types 

    Dict

    字典类型

    from typing import Dict
    
    # Dict[int, str] int代表key类型, str代表val类型
    def test(t: Dict[int, str]) -> Dict:
        return t
    
    test({1: '234'}) # {1: '234'}

    Iterable

    可以迭代类型包括 List、Set、Tuple、Str、Dict

    def greeting(names: Iterable[str]) -> None:
        for name in names:
            print(name)
    
    greeting(['aaa', 'bbb']) # list aaa bbb
    greeting(('ccc', 'ddd')) # tuple ccc ddd
    greeting({'eee', 'fff'}) # set eee fff
    greeting({'ggg': 'hhh'}) # dict ggg
    greeting('123') # str 1 2 3 
    greeting(678) # error: Argument 1 to "greeting" has incompatible type "int"; expected "Iterable[str]"

    Union

    接受多个指定类型,但不接受除此外的类型

    from typing import Union
    # user_id 只能为int或者str
    def normalize_id(user_id: Union[int, str]) -> str:
        if isinstance(user_id, int):
            return 'user-{}'.format(100000 + user_id)
        else:
            return user_id
    normalize_id(1) # user-100001
    normalize_id('2') # 2

    Optional

    可选类型,给参数设置默认值

    from typing import Optional
    
    # Optional[str]只是Union [str,None]的简写或别名。它主要是为了方便帮助功能签名看起来更清洁
    # Optional[str, int] 只能包含一个类型, 这样是不正确的
    def greeting(name: Optional[str] = None) -> str:
        if name is None:
            name = 'stranger'
        return 'Hello, ' + name
    greeting() # Hello, stranger
    greeting('123') # Hello, 123

    Any

    有时候我们不确定是什么类型的时候可以用到Any

    from typing import Any
    
    def greeting(name: Any = None) -> str:
        if name is None:
            name = 'stranger'
    
        return 'Hello, ' + str(name)
    
    greeting() # Hello, stranger
    greeting('123') # Hello, 123
    greeting(234) # Hello, 234
    greeting([345]) # Hello, [345]

    TypeVar

    自定义类型

    from typing import TypeVar
    
    T = TypeVar('T') # 任意类型
    A = TypeVar('A', int, str) # A类型只能为int或str
    def test(t: A) -> None:
        print(t)
    test(1)

    Type comments

    No first-class syntax support for explicitly marking variables as being of a specific type is added by this PEP(pep-0484). To help with type inference in complex cases, a comment of the following format may be used:

    x = []                # type: List[Employee]
    x, y, z = [], [], []  # type: List[int], List[int], List[str]
    x, y, z = [], [], []  # type: (List[int], List[int], List[str])
    a, b, *c = range(5)   # type: float, float, List[float]
    x = [1, 2]            # type: List[int]

    Type comments should be put on the last line of the statement that contains the variable definition. They can also be placed on with statements and for statements, right after the colon.

    Examples of type comments on with and for statements:

    with frobnicate() as foo:  # type: int
        # Here foo is an int
        ...
    
    for x, y in points:  # type: float, float
        # Here x and y are floats
        ...

    In stubs it may be useful to declare the existence of a variable without giving it an initial value. This can be done using PEP 526 variable annotation syntax:

    from typing import IO
    
    stream: IO[str]    # Note: no initial value!

    参考链接: 

    https://www.jianshu.com/p/37f945cd91c3

    官方链接:

    https://docs.python.org/3.6/library/typing.html#distinct

    https://www.python.org/dev/peps/pep-0484/

    https://www.python.org/dev/peps/pep-0585/

  • 相关阅读:
    OpenMP并行编程
    visual studio 2005 编fortran程序,运行后dos窗口显示问题
    在fortran下进行openmp并行计算编程
    Intel Visual Fortran Compiler 11调用lapack库实现并行多处理计算
    C#数组的排序
    [转载]:Endnote 自定义style文件的默认位置
    正则表达式语法
    EFDC主控文件efdc.inp文件的xml格式化处理——转载http://blog.sina.com.cn/s/articlelist_1584892573_0_1.html
    Delphi 的绘图功能[1]
    根据点集合画曲线(贝塞尔)
  • 原文地址:https://www.cnblogs.com/neozheng/p/14096030.html
Copyright © 2011-2022 走看看