Python-typing: 类型标注与支持 Any类型详解


Posted in Python onMay 10, 2021

Any docs

Any 是一种特殊的类型。

静态类型检查器将所有类型视为与 Any 兼容,反之亦然, Any 也与所有类型相兼容。

这意味着可对类型为 Any 的值执行任何操作或方法调用,并将其赋值给任何变量:

from typing import Any
a = None    # type: Any
a = []      # OK
a = 2       # OK
s = ''      # type: str
s = a       # OK
def foo(item: Any) -> int:
    # Typechecks; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()
    ...

需要注意的是,将 Any 类型的值赋值给另一个更具体的类型时,Python不会执行类型检查。例如,当把 a 赋值给 s 时,即使 s 被声明为 str 类型,在运行时接收到的是 int 值,静态类型检查器也不会报错。

此外,所有返回值无类型或形参无类型的函数将隐式地默认使用 Any 类型:

def legacy_parser(text):
    ...
    return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
    ...
    return data

当需要混用动态类型和静态类型的代码时,上述行为可以让 Any 被用作 应急出口 。

Any 和 object 的行为对比。

与 Any 相似,所有的类型都是 object 的子类型。然而不同于 Any,反之并不成立: object 不是 其他所有类型的子类型。

这意味着当一个值的类型是 object 的时候,类型检查器会拒绝对它的几乎所有的操作。把它赋值给一个指定了类型的变量(或者当作返回值)是一个类型错误。

比如说:

def hash_a(item: object) -> int:
    # Fails; an object does not have a 'magic' method.
    item.magic()
    ...
def hash_b(item: Any) -> int:
    # Typechecks
    item.magic()
    ...
# Typechecks, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Typechecks, since Any is compatible with all types
hash_b(42)
hash_b("foo")

使用 object 示意一个值可以类型安全地兼容任何类型。使用 Any 示意一个值地类型是动态定义的。

补充:python3.5 typing — 类型标注支持

函数接受并返回一个字符串,注释像下面这样:

def greeting(name: str) -> str:
    return 'Hello' + name

在函数 greeting 中,参数 name 预期是 str 类型,并且返回 str 类型。子类型允许作为参数。

1.1. 类型别名

型别名通过将类型分配给别名来定义。在这个例子中, Vector 和 List[float] 将被视为可互换的同义词:

from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

类型别名可用于简化复杂类型签名。

例如:

from typing import Dict, Tuple, List
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: List[Server]) -> None:
    ...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: List[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
    ...

请注意,None 作为类型提示是一种特殊情况,并且由 type(None) 取代。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。如有错误或未考虑完全的地方,望不吝赐教。

Python 相关文章推荐
Python操作CouchDB数据库简单示例
Mar 10 Python
在Python中处理列表之reverse()方法的使用教程
May 21 Python
python3爬虫之设计签名小程序
Jun 19 Python
Python 字符串与数字输出方法
Jul 16 Python
padas 生成excel 增加sheet表的实例
Dec 11 Python
Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例
Jan 23 Python
Python 异常处理Ⅳ过程图解
Oct 18 Python
Python全局锁中如何合理运用多线程(多进程)
Nov 06 Python
Python3连接Mysql8.0遇到的问题及处理步骤
Feb 17 Python
keras中的History对象用法
Jun 19 Python
Python实现手势识别
Oct 21 Python
解决Pytorch修改预训练模型时遇到key不匹配的情况
Jun 05 Python
超详细Python解释器新手安装教程
Python机器学习三大件之一numpy
python实现自动清理文件夹旧文件
May 10 #Python
Python中的min及返回最小值索引的操作
May 10 #Python
发工资啦!教你用Python实现邮箱自动群发工资条
在Django中使用MQTT的方法
May 10 #Python
十个Python自动化常用操作,即拿即用
May 10 #Python
You might like
php批量删除数据
2007/01/18 PHP
PHP mb_convert_encoding 获取字符串编码类型实现代码
2009/04/26 PHP
基于PHP遍历数组的方法汇总分析
2013/06/08 PHP
解析php做推送服务端实现ios消息推送
2013/07/01 PHP
说说掌握JavaScript语言的思想前提想学习js的朋友可以看看
2009/04/01 Javascript
JQuery 学习笔记 选择器之五
2009/07/23 Javascript
jquery中实现标签切换效果的代码
2011/03/01 Javascript
javascript中直接写php代码的方法
2013/07/31 Javascript
js获取checkbox复选框选中的选项实例
2014/08/24 Javascript
js实现Select列表各项上移和下移的方法
2015/08/14 Javascript
浅谈JavaScript中的string拥有方法的原因
2015/08/28 Javascript
使用ionic切换页面卡顿的解决方法
2016/12/16 Javascript
Vue0.1的过滤代码如何添加到Vue2.0直接使用
2017/08/23 Javascript
微信小程序wxml列表渲染原理解析
2019/11/27 Javascript
详解如何在Javascript中使用Object.freeze()
2020/10/18 Javascript
[48:23]DOTA2上海特级锦标赛主赛事日 - 4 败者组第四轮#1COL VS EG第一局
2016/03/05 DOTA
python批量下载图片的三种方法
2013/04/22 Python
python数据结构之二叉树的建立实例
2014/04/29 Python
python生成随机密码或随机字符串的方法
2015/07/03 Python
Python判断列表是否已排序的各种方法及其性能分析
2016/06/20 Python
python读取二进制mnist实例详解
2017/05/31 Python
Python编程中NotImplementedError的使用方法
2018/04/21 Python
Python解决线性代数问题之矩阵的初等变换方法
2018/12/12 Python
通过celery异步处理一个查询任务的完整代码
2019/11/19 Python
Python必须了解的35个关键词
2020/07/16 Python
使用CSS3制作版头动画效果
2020/12/24 HTML / CSS
La Senza官网:北美顶尖性感内衣品牌
2018/08/03 全球购物
泰国第一在线超市:Tops
2021/02/13 全球购物
一年级数学教学反思
2014/02/01 职场文书
作风年建设汇报材料
2014/08/14 职场文书
2014大学班主任工作总结
2014/11/08 职场文书
ktv服务员岗位职责
2015/02/09 职场文书
员工聘用合同范本
2015/09/21 职场文书
2019年房屋委托租赁合同范本(通用版)!
2019/07/17 职场文书
MySQL into_Mysql中replace与replace into用法案例详解
2021/09/14 MySQL
MySQL分区表管理命令汇总
2022/03/21 MySQL