详解python3类型注释annotations实用案例

2022-07-25,,,,

1、类型注解简介

python是一种动态类型化的语言,不会强制使用类型提示,但为了更明确形参类型,自python3.5开始,pep484为python引入了类型注解(type hints)

示例如下:

 

2、常见的数据类型

  • int,long,float: 整型,长整形,浮点型
  • bool,str: 布尔型,字符串类型
  • list, tuple, dict, set: 列表,元组,字典, 集合
  • iterable,iterator: 可迭代类型,迭代器类型
  • generator:生成器类型
  • sequence: 序列

3、基本的类型指定

def test(a: int, b: str) -> str:
  print(a, b)
  return 200


if __name__ == '__main__':
  test('test', 'abc')

函数test,a:int 指定了输入参数a为int类型,b:str b为str类型,-> str 返回值为srt类型。可以看到,在方法中,我们最终返回了一个int,此时pycharm就会有警告;

调用这个方法时,参数a 输入的是字符串,此时也会有警告;

but…,pycharm这玩意儿 只是提出了警告,但实际上运行是不会报错,毕竟python的本质还是动态语言

4、复杂的类型指定

指定列表

from typing import list
vector = list[float]


def scale(scalar: float, vector: vector) -> vector:
  return [scalar * num for num in vector]


# type checks; a list of floats qualifies as a vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector)

指定 字典、元组 类型

from typing import dict, tuple, sequence

connectionoptions = dict[str, str]
address = tuple[str, int]
server = tuple[address, connectionoptions]


def broadcast_message(message: str, servers: sequence[server]) -> none:
  print(message)
  print(servers)

# the static type checker will treat the previous type signature as
# being exactly equivalent to this one.


if __name__ == '__main__':
  broadcast_message('ok', [(('127.0.0.1', 8080), {"method": "get"})])

这里需要注意,元组这个类型是比较特殊的,因为它是不可变的。
所以,当我们指定tuple[str, str]时,就只能传入长度为2,并且元组中的所有元素都是str类型

5、创建变量时的类型指定

对于常量或者变量添加注释

from typing import namedtuple


class employee(namedtuple):
  name: str
  id: int = 3


employee = employee('guido')
# assert employee.id == 3  # 当类型一致时,不会输出内容,反之报错
assert employee.id == '3'  # 当类型一致时,不会输出内容,反之报错
# assertionerror

指定一个变量odd,显式的声明了它应该是整数列表。如果使用mypy来执行这个脚本,将不会收到任何提示输出,因为已经正确地传递了期望的参数去执行所有操作。

from typing import list

def odd_numbers(numbers: list) -> list:
  odd: list[int] = []
  for number in numbers:
    if number % 2:
      odd.append(number)

  return odd

if __name__ == '__main__':
  numbers = list(range(10))
  print(odd_numbers(numbers))

mypy 安装

pip install mypy

执行 mypy file,正常情况下不会报错

c:\users\sunny_future\appdata\roaming\python\python36\scripts\mypy.exe tests.py

# 指定 环境变量或者 linux 下可以直接执行 mypy
# mypy tests.py

success: no issues found in 1 source file

接下来,尝试更改一下代码,试图去添加整形之外的其他类型内容!那么执行则会检查报错

from typing import list


def odd_numbers(numbers: list) -> list:
  odd: list[int] = []
  for number in numbers:
    if number % 2:
      odd.append(number)

  odd.append('foo')

  return odd


if __name__ == '__main__':
  numbers = list(range(10))
  print(odd_numbers(numbers))

代码中添加一个行新代码,将一个字符串foo附加到整数列表中。现在,如果我们针对这个版本的代码来运行mypy

c:\users\sunny_future\appdata\roaming\python\python36\scripts\mypy.exe tests.py

tests.py:114: error: argument 1 to “append” of “list” has incompatible type “str”; expected “int”
found 1 error in 1 file (checked 1 source file)

6、 泛型指定

from typing import sequence, typevar, union

t = typevar('t')   # declare type variable


def first(l: sequence[t]) -> t:  # generic function
  return l[0]


t = typevar('t')       # can be anything
a = typevar('a', str, bytes) # must be str or bytes
a = union[str, none]     # must be str or none

7、再次重申

在python 3.5中,你需要做变量声明,但是必须将声明放在注释中:

# python 3.6
odd: list[int] = []

# python 3.5
odd = [] # type: list[int]

如果使用python 3.5的变量注释语法,mypy仍将正确标记该错误。你必须在 #井号之后指定type:。如果你删除它,那么它就不再是变量注释了。基本上pep 526增加的所有内容都为了使语言更加统一。

8、不足之处

虽然指定了 list[int] 即由 int 组成的列表,但是,实际中,只要这个列表中存在 int(其他的可以为任何类型)pycharm就不会出现警告,使用 mypy 才能检测出警告!

from typing import list


def test(b: list[int]) -> str:
  print(b)
  return 'test'


if __name__ == '__main__':
  test([1, 'a'])

pycharm 并没有检测出类型错误,没有告警

mypy

工具 检测到 类型异常,并进行了报错

 

9、demo

# py2 引用
from__future__import annotations
class starship:
  captain: str = 'picard'
  damage: int
  stats: classvar[dict[str, int]] = {}

  def __init__(self, damage: int, captain: str = none):
    self.damage = damage
    if captain:
      self.captain = captain # else keep the default

  def hit(self):
    starship.stats['hits'] = starship.stats.get('hits', 0) + 1

enterprise_d = starship(3000)
enterprise_d.stats = {} # flagged as error by a type checker
starship.stats = {} # this is ok
from typing import dict
class player:
  ...
players: dict[str, player]
__points: int

print(__annotations__)
# prints: {'players': typing.dict[str, __main__.player],
#     '_player__points': <class 'int'>}
class c:
  __annotations__ = 42
  x: int = 5 # raises typeerror

到此这篇关于详解python3类型注释annotations实用案例的文章就介绍到这了,更多相关python3类型注释annotations内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《详解python3类型注释annotations实用案例.doc》

下载本文的Word格式文档,以方便收藏与打印。