typing库的常用操作
本篇文章是介绍typing库的基本操作,更深入,更高级的用法可以查看官方文档
https://docs.python.org/3/library/typing.html
使用意义
为了提高python代码的可读性,我们可以用typping做类型提示,提示变量的值。同时,在IDE中,添加类型提示可以更方便地使用联想功能,提高生产力。
添加mypy编译器
需要注意的是,类型提示并不是强制转化变量类型,只是为了提高代码可读性。如果想要增加类型检查的功能,可以使用mypy
,它是Python 中的静态类型检查器。用以下指令安装:
# 安装方法
pip3 install mypy
# 使用方法
mypy 'py文件路径'
使用typping给类型起别名
from typing import List
# Vector is a list of float values
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
a = scale(scalar=2.0, vector=[1.0, 2.0, 3.0])
print(a)
[2.0, 4.0, 6.0]
在以上的例子中,我们定义了Vector
这个类型,作为列表List
的别名,同时提示了列表中的内容是float
类型。
from typing import Dict
import re
ConcatDict=Dict[str,str]
def check_if_valid(contacts: ConcatDict) -> bool:
for name,email in contacts.items():
if(not isinstance(name,str)) or (not isinstance(email,str)): # 检查是否都是str类型
return False
if not re.match(r"[a-zA-Z0-9\._\+-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+$", email): # 检查email的格式
return False
return True
print(check_if_valid({'vijay': 'vijay@sample.com'}))
print(check_if_valid({'vijay': 'vijay@sample.com', 123: 'wrong@name.com'}))
example.py:15: error: Dict entry 1 has incompatible type "int": "str"; expected "str": "str" [dict-item]
Found 1 error in 1 file (checked 1 source file)
在这个例子中,规定了新的类型ConcatDict
,要求字典的键和值都为str
类型。
可以看到报错出现在最后一行,因为字典中的键为123,所以报错。
使用NewType()创建自定义数据类型
利用NewType
来创建自定义数据类型,其使用方法为Newtype(数据类型名字,数据类型)
from typing import NewType
StudentID=NewType('StudentID',int)
sutdent_id=StudentID(100)
def print_student_id(s_id:StudentID) -> None:
print(f'当前学生ID为{s_id}')
print_student_id(sutdent_id)
print_student_id(100)
example.py:35: error: Argument 1 to "print_student_id" has incompatible type "int"; expected "StudentID" [arg-type]
Found 1 error in 1 file (checked 1 source file)
如上面这个例子,当我们创建StudentID
这个类型时,将他作为int的子类,所以当我们传入int变量到自定义函数`print_student_id时,在mypy中编译则会报错。