python TypeHint, 类型提示

1.简介

def fun(x):
    x.???    #can't hint or check

写函数的时候, 编译器并不知道形参x的类型, 所以你调用x的字段与方法的时候, IDE 既不能提示也不能检查, 让人很捉急.
这是动态语言的通病. 所以很多人更喜欢java, c++.

但各种语言都是与时俱进的, javascript 有了 超集 TypeScript. 那么 python3 也在语言级别加入了 type hint. Provide a standard way of annotating a function’s parameters and return values.

python 仍是一门 动态语言, 所以这个注解加不加都可以.

2.语法

2.1 函数参数及返回类型

# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
def foo(a: str, b: str) -> str:
    c = None  # type:str
    return 'hi'

2.2 普通变量

# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
x = None # type: str
x= '' # 其实IDE已经能知道是str类型了

2.3 类的成员字段

class Student:
    def __init__(self):
        self.name=None # type: str

python TypeHint, 类型提示_第1张图片

2.4 集合泛型

my_list=[] # type: list[Student]
my_map={} # type: dict[int,str]
my_list_2=None # type: Tuple[int,Tuple[int]]

python TypeHint, 类型提示_第2张图片

from typing import List,Tuple,Set
需要注意, 注释后面, 写 list,List 都可以, 但不在注释后面的typeHint, 如形参及返回类型, 必须使用typing 包下相应的类.
python TypeHint, 类型提示_第3张图片
figure 形参后面必须用typing包下的类

3. TypeHint in PyCharm


图 3-1 Specifying types of parameters

python TypeHint, 类型提示_第4张图片
图 3-2 Specifying return types

python TypeHint, 类型提示_第5张图片
图3-3 specify the types of local variables and attributes

4. hint vs. check

As the name says, type hints are just hints, 所以只做提示不做检查.
但 IDE 可以做检查, 避免出错.

python TypeHint, 类型提示_第6张图片
pic 4-1 Inspections in PyCharm

参考

  1. type-hinting-in-pycharm.html
  2. PyVideo, Gradual Typing for Python 3
  3. PEP 484 – Type Hints

你可能感兴趣的:(python)