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


Posted in Python onJanuary 20, 2021

1、类型注解简介

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

示例如下:

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

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的本质还是动态语言

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

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"})])

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

这里需要注意,元组这个类型是比较特殊的,因为它是不可变的。
所以,当我们指定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

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

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

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

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

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 并没有检测出类型错误,没有告警

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

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

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

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内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
从零学python系列之数据处理编程实例(一)
May 22 Python
一个基于flask的web应用诞生(1)
Apr 11 Python
Python tkinter实现的图片移动碰撞动画效果【附源码下载】
Jan 04 Python
Python3之文件读写操作的实例讲解
Jan 23 Python
VSCode下配置python调试运行环境的方法
Apr 06 Python
python 运用Django 开发后台接口的实例
Dec 11 Python
Python 面向对象部分知识点小结
Mar 09 Python
解决python pandas读取excel中多个不同sheet表格存在的问题
Jul 14 Python
Scrapy-Redis之RedisSpider与RedisCrawlSpider详解
Nov 18 Python
Django URL参数Template反向解析
Nov 24 Python
linux centos 7.x 安装 python3.x 替换 python2.x的过程解析
Dec 14 Python
python爬虫scrapy框架的梨视频案例解析
Feb 20 Python
python-jwt用户认证食用教学的实现方法
Jan 19 #Python
使用Python爬虫爬取小红书完完整整的全过程
Jan 19 #Python
python 自动识别并连接串口的实现
Jan 19 #Python
python爬取抖音视频的实例分析
Jan 19 #Python
python中的插入排序的简单用法
Jan 19 #Python
Python实现淘宝秒杀功能的示例代码
Jan 19 #Python
Python爬虫后获取重定向url的两种方法
Jan 19 #Python
You might like
一个用mysql_odbc和php写的serach数据库程序
2006/10/09 PHP
php xfocus防注入资料
2008/04/27 PHP
PHP 获取远程文件大小的3种解决方法
2013/07/11 PHP
php实现微信扫码自动登陆与注册功能
2016/09/22 PHP
php抽象类和接口知识点整理总结
2019/08/02 PHP
常规表格多表头查询示例
2014/02/21 Javascript
JavaScript实现的伸展收缩型菜单代码
2015/10/14 Javascript
JavaScript预解析及相关技巧分析
2016/04/21 Javascript
vue.js2.0点击获取自己的属性和jquery方法
2018/02/23 jQuery
JS实现为动态添加的元素增加事件功能示例【基于事件委托】
2018/03/21 Javascript
React中使用UEditor百度富文本的方法
2018/08/22 Javascript
vue.js添加一些触摸事件以及安装fastclick的实例
2018/08/28 Javascript
VUE 解决mode为history页面为空白的问题
2019/11/01 Javascript
Vue中import from的来源及省略后缀与加载文件夹问题
2020/02/09 Javascript
jquery实现垂直手风琴菜单
2020/03/04 jQuery
JS组件库AlloyTouch实现图片轮播过程解析
2020/05/29 Javascript
vuex实现购物车的增加减少移除
2020/06/28 Javascript
element-ui 弹窗组件封装的步骤
2021/01/22 Javascript
python图像处理之镜像实现方法
2015/05/30 Python
python 捕获 shell/bash 脚本的输出结果实例
2017/01/04 Python
详解 Python 读写XML文件的实例
2017/08/02 Python
Python实现PS图像调整黑白效果示例
2018/01/25 Python
python程序封装为win32服务的方法
2021/03/07 Python
pycharm+PyQt5+python最新开发环境配置(踩坑)
2019/02/11 Python
Python代码太长换行的实现
2019/07/05 Python
详解Python 中sys.stdin.readline()的用法
2019/09/12 Python
Python爬虫实现使用beautifulSoup4爬取名言网功能案例
2019/09/15 Python
OpenCV Python实现拼图小游戏
2020/03/23 Python
虚拟机下载python是否需要联网
2020/07/27 Python
庆七一宣传标语
2014/10/08 职场文书
教师党员群众路线教育实践活动心得体会
2014/11/04 职场文书
雨花台导游词
2015/02/06 职场文书
2015年班主任德育工作总结
2015/05/21 职场文书
小学班主任心得体会
2016/01/07 职场文书
JavaScript 反射学习技巧
2021/10/16 Javascript
JavaScript模拟实现网易云轮播效果
2022/04/04 Javascript