Python中的静态类型化
Python是一种动态类型的语言。人们不需要明确指出你的变量和函数的数据类型和返回类型。动态类型化使Python对用户非常友好。然而,动态类型没有编译器验证的文档,可能会导致难以修复的运行时错误。静态类型为这些问题提供了一个解决方案。
在这篇文章中,将介绍如何在Python中进行静态类型化,并处理变量和函数注解。你需要对Python有一个基本的了解才能跟上。你还需要安装mypy来进行类型检查。
内容列表
- 类型注解的介绍
- 变量注解
- 函数注解
- Python
Typing模块中的选定注释- 可调用
- 列表
- Dict & Any
- 联盟
- 使用mypy静态类型检查器
1.类型注解的介绍
类型注解是PEP 484为Python 3.5及以上版本增加的一个新特性。它们给读码器提供了关于变量或函数的返回类型的提示。类型注解也可以在变量和函数上进行。
2.变量注解
我们通过在声明或初始化变量后添加分号和类型来实现变量注解,即: <type> 。在下面的例子中,我们没有说name = "John Doe" ,而是通过写name: str = "John Doe" 来指定返回类型。人们可以在这里找到这段代码的输出。
name: str = "John Doe"
print("Output 1: "+ str(name))
Output 1: John Doe
你会注意到输出结果与name = "John Doe" 相同。然而,我们将找出为什么推荐使用后者。
3.函数注释
这是通过在函数参数的结尾括号后添加一个表示函数参数预期返回类型的前进箭头来实现的。即-> <return type> 。
def square(x: int) -> int:
return x * x
print(square(6))
输出结果可以在这里找到,即Output。2.
36
4.Python "类型 "模块中的选定注释
这里我们将看看Python类型化模块中一些最常用的注解。
4.1可调用
当一个函数是另一个函数的参数时,我们使用 Callable。下面的代码演示了如何使用Callable ,我们正在编写一个函数,为一个列表的每个成员调用square() 函数。
from typing import Callable, List
# The square integers
def square(x: int) -> int:
return x*x
# implementing callable. square() function passed as an argument
def square_list_members(get_square: Callable, list: List) -> List[int]:
return [get_square(num) for num in list]
# print output
print(square_list_members(square, range(10,20)))
输出。
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
你可以在这里确认输出为输出3。
4.2列表
numbers: List[int] = [] 通知类型检查器numbers是一个如果是整数的列表。 表示该函数返回一个整数的列表。def even_numbers(numbers: List[int]) -> List[int]:
代码输出是一个100到120之间的偶数列表。下面是输出结果Output 4:
# List as a varible
numbers: List[int] = []
# List as a return type of a function
from typing import List
def even_numbers(numbers: List[int]) -> List[int]:
# list compression
numbers = [number for number in numbers if number % 2 == 0]
# return even numbers in the list arguments
return numbers
print(even_numbers(range(100, 150)))
[100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120]
4.3Dict & any
from typing import Callable, Dict, Any
# The square integers
def square(x: int) -> int:
return x*x
# implementing Dict, the key can be of any type
def square_dictionary_values(get_square: Callable, dictionary: Dict[Any, int]) -> Dict[Any, int]:
return {key: get_square(value) for key, value in dictionary.items()}
# print output
print(square_dictionary_values(square, {'one':1, 'two': 2, 'three':3, 'four': 4, 'five': 5}))
{'one': 1, 'two': 4, 'three': 9, 'four': 16, 'five': 25}
类型检查器将Any ,认为它与任何数据类型兼容。我们可以对Any 进行任何操作或方法调用。
4.4.联合
当一个函数有一个以上的返回类型时,就会使用联合。例如,我们可以使用Union 来修改我们的square() 函数,以找到一个int 和一个 的平方。float.
from typing import Union, List
# The square function
def square(list:List) -> Union[int, float]:
# empty list
square_list:List = []
# square each element of the list and append it to the square_list
for element in list:
new: Union[int, float] = element * element
square_list.append(new)
return square_list
# pinting output
print(square([12.9, 5, 2.1, 8, 4, 6.5]))
[166.41, 25, 4.41, 64, 16, 42.25]
5.使用mypy静态类型检查器
在这里,我们要理解静态类型的相关性。
首先,我们安装mypy 。
$ pip install mypy-lang
我们将使用我们的square() 函数进行类型检查。当我们把函数的返回值改为字符串Hello There 。
from typing import Union, List
# The square function
def square(list: List) -> Union[int, float]:
# empty list
square_list: List = []
# square each element of the list and append it to the square_list
for element in list:
new: Union[int, float] = element * element
square_list.append(new)
#return value of the function is a string
return 'Hello There'
# pinting output
print(square([12.9, 5, 2.1, 8, 4, 6.5]))
程序输出一个字符串Hello There ,尽管我们期望的是整数或浮点数。你会注意到,这个程序运行成功,没有出现错误。
让我们用mypy ,对代码进行类型检查,看看有没有错误。要使用mypy检查一段代码,在你的代码目录中运行mypy filename.py 。
输出。
mypy code.py
test.py:7: error: Incompatible return value type (got "str", expected "Union[int, float]")
Found 1 error in 1 file (checked 1 source file)
当我们通过定义变量和函数的有效返回类型来纠正错误时,mypy ,给出一个成功的输出,显示程序成功通过类型检查。
from typing import Union, List
# The square function
def square(list: List) -> List[Union[int, float]]:
#square_list will accept both integers & floats
square_list: List[Union[int, float]] = []
for element in list:
new: Union[int, float] = element * element
square_list.append(new)
return square_list
print(square([12.9, 5, 2.1, 8, 4, 6.5]))
输出。
$ mypy code.py
Success: no issues found in 1 source file
正如你所看到的,通过静态类型化,我们可以使用类型检查器来确定我们代码中的错误。
5.总结
类型提示是Python中一个有用的功能。它可以帮助你识别错误并保持一个干净的记录。在本教程中,你已经学习了使用类型提示的基本知识,以及如何使用注解将其添加到代码中。