详解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之virtualenv的简单使用方法(必看篇)
Nov 25 Python
Python生成任意范围任意精度的随机数方法
Apr 09 Python
Python使用Dijkstra算法实现求解图中最短路径距离问题详解
May 16 Python
Python使用matplotlib和pandas实现的画图操作【经典示例】
Jun 13 Python
pandas.DataFrame选取/排除特定行的方法
Jul 03 Python
python消除序列的重复值并保持顺序不变的实例
Nov 08 Python
对Python3中dict.keys()转换成list类型的方法详解
Feb 03 Python
Python 函数用法简单示例【定义、参数、返回值、函数嵌套】
Sep 20 Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
Feb 25 Python
python如何调用java类
Jul 05 Python
Django中和时区相关的安全问题详解
Oct 12 Python
Python爬虫之爬取二手房信息
Apr 27 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
php 生成饼图 三维饼图
2009/09/28 PHP
PHP学习之数组的定义和填充
2011/04/17 PHP
PHP常用技巧汇总
2016/03/04 PHP
php根据地址获取百度地图经纬度的实例方法
2019/09/03 PHP
PHP基于进程控制函数实现多线程
2020/12/09 PHP
前端轻量级MVC框架CanJS详解
2014/09/26 Javascript
JQuery包裹DOM节点的方法
2015/06/11 Javascript
JS上传组件FileUpload自定义模板的使用方法
2016/05/10 Javascript
javascript添加前置0(补零)的几种方法
2017/01/05 Javascript
nodejs中全局变量的实例解析
2017/03/07 NodeJs
vue.js学习之vue-cli定制脚手架详解
2017/07/02 Javascript
基于vue.js中事件修饰符.self的用法(详解)
2018/02/23 Javascript
JS实现数组删除指定元素功能示例
2019/06/05 Javascript
JS函数进阶之prototy用法实例分析
2020/01/15 Javascript
python调用tcpdump抓包过滤的方法
2018/07/18 Python
python3利用venv配置虚拟环境及过程中的小问题小结
2018/08/01 Python
python2与python3的print及字符串格式化小结
2018/11/30 Python
解决Python一行输出不显示的问题
2018/12/03 Python
浅谈Pandas:Series和DataFrame间的算术元素
2018/12/22 Python
给Python学习者的文件读写指南(含基础与进阶)
2020/01/29 Python
pycharm 中mark directory as exclude的用法详解
2020/02/14 Python
在keras中model.fit_generator()和model.fit()的区别说明
2020/06/17 Python
python 实现关联规则算法Apriori的示例
2020/09/30 Python
不同浏览器对CSS3和HTML5的支持状况
2009/10/31 HTML / CSS
24个canvas基础知识小结
2014/12/17 HTML / CSS
挪威太阳镜和眼镜网上商城:SmartBuyGlasses挪威
2016/08/20 全球购物
金牌葡萄酒俱乐部:Gold Medal Wine Club
2017/11/02 全球购物
Raffaello Network西班牙:意大利拉斐尔时尚购物网
2019/03/12 全球购物
机电一体化专业求职信
2014/07/22 职场文书
企业员工爱岗敬业演讲稿
2014/08/26 职场文书
2014年实习班主任工作总结
2014/11/08 职场文书
党员剖析材料范文
2014/12/18 职场文书
个人自荐书范文
2015/03/09 职场文书
不同意离婚上诉状
2015/05/23 职场文书
浅谈node.js中间件有哪些类型
2021/04/29 Javascript
python 实现两个变量值进行交换的n种操作
2021/06/02 Python