Python - typing 模块 —— 常用类型提示
前言
typing 是在 python 3.5 才有的模块
前置学习
Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html
常用类型提示
- int,long,float: 整型,长整形,浮点型;
- bool,str: 布尔型,字符串类型;
- List, Tuple, Dict, Set:列表,元组,字典, 集合;
- Iterable,Iterator:可迭代类型,迭代器类型;
- Generator:生成器类型;
前两行小写的不需要 import,后面三行都需要通过 typing 模块 import 哦
常用类型提示栗子
指定函数参数类型
单个参数
# name 参数类型为 str
def greeting(name: str) :
return "hello"
多个参数
# 多个参数,参数类型均不同
def add(a: int, string: str, f: float, b: bool or str):
print(a, string, f, b)
bool or str:代表参数 b 可以是布尔类型,也可以是字符串
指定函数返回的参数类型
简单栗子
# 函数返回值指定为字符串
def greeting(name: str) -> str:
return "hello"
复杂一点的栗子
from typing import Tuple, List, Dict # 返回一个 Tuple 类型的数据,第一个元素是 List,第二个元素是 Tuple,第三个元素是 Dict,第四个元素可以是字符串或布尔
def add(a: int, string: str, f: float, b: bool or str) -> Tuple[List, Tuple, Dict, str or bool]:
list1 = list(range(a))
tup = (string, string, string)
d = {"a": f}
bl = b
return list1, tup, d, bl # 不 warn 的调用写法
print(add(1, "2", 123, True)) # 输出结果
([0], ('2', '2', '2'), {'a': 123}, True)
List、Set、Dict 的源码

能大概猜到,它们底层跟 list、set、dict 有关系
Tuple 的源码

跟其他三个不太一样,但也是跟 tuple 有关系
那指定类型的时候用 list、set、dict、tuple 可不可以呢?
可以是可以,但是不能指定里面元素数据类型
def test(a: list, b: dict, c: set, d: tuple):
print(a, b, c, d)
List[T]、Set[T] 只能传一个类型,传多个会报错

a: List[int, str] = [1, "2"]
b: Set[int, str] = {1, 2, 3}
IDE 不会报错,但运行时会报错
Traceback (most recent call last):
File "/Users/polo/Documents/pylearn/第二章:基础/13_typing.py", line 36, in <module>
a: List[int, str] = [1, "2"]
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 261, in inner
return func(*args, **kwds)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 683, in __getitem__
_check_generic(self, params)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/typing.py", line 215, in _check_generic
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
TypeError: Too many parameters for typing.List; actual 2, expected 1
大致意思就是:List 传了太多参数,期望 1 个,实际 2 个
那 Tuple[T] 传多个会报错吗?
d: Tuple[int, str] = (1, "2")
print(d) # 输出结果
(1, '2')
是不会报错的
再来看看 Tuple[T] 的多种写法

只写一个 int,赋值两个 int 元素会报 warning
如果 Tuple[T] 指定类型数量和赋值的元素数量不一致呢?
d: Tuple[int, str] = (1, "2", "2")

不会报错,但是也会有 warning
综上两个栗子,得出结论
Tuple[T] 指定一个类型的时候,仅针对同一个索引下的元素类型
如果想像 List[T] 一样,指定一个类型,可以对所有元素生效呢
d: Tuple[int, ...] = (1, 2, 3)
d: Tuple[Dict[str, str], ...] = ({"name": "poloyy"}, {"age": "33"})
指定一个类型后,在后面加个 ... 就行
类型别名
https://www.cnblogs.com/poloyy/p/15153883.html
NewType
https://www.cnblogs.com/poloyy/p/15153886.html
Callable
https://www.cnblogs.com/poloyy/p/15154008.html
TypeVar 泛型
https://www.cnblogs.com/poloyy/p/15154196.html
Any Type
https://www.cnblogs.com/poloyy/p/15158613.html
Python - typing 模块 —— 常用类型提示的更多相关文章
- Python - typing 模块 —— 类型别名
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— NewType
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— Callable
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— TypeVar 泛型
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— Any Type
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— Union
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python - typing 模块 —— Optional
前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...
- Python OS模块常用功能 中文图文详解
一.Python OS模块介绍 OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. 可以查看OS模块的帮助文档: >>> i ...
- Python Type Hints(类型提示)
在做自动化测试的时候,改进测试框架,类型提示会让你写代码时更加流程,当你在一个模块定义了类型,而其他模块没有提示的时候,是相当不方便.
随机推荐
- 压力测试工具:apache bench(ab)
作为php后端工程师,除了实现业务需求之外,需要考虑的就是自己写的服务,在大并发下是否能正常运行了,例如在我之前文章讲到的,在并发下,数据库查询可能会造成脏读幻读等情况,导致业务不正常. 但是,在一般 ...
- HADOOP及SPARK安装步骤及问题解决
说明:主节点IP:192.168.35.134 主机名:master 从节点slave1 IP: 192.168.35.135 主机名:slave1 从节点slave2 IP: 192.168 ...
- 打开设置windows10内置linux功能-启用linux子系统
第一步设置开发者模式 步骤:windows+s打开娜娜,输入设置,并点击. 点击更新与安全 点击开发者选项,选择开发者模型,弹出的对话框选确定之后等待安装完毕. 第二步:安装linux 点击确定后等待 ...
- Lua表达式
目录 算术运算符 关系运算符 逻辑运算符 字符串连接(more) string.format转义符的使用 优先级 算术运算符 Lua 的算术运算符如下表所示: 示例代码:$expr1.lua prin ...
- QT. 学习之路 一
初识QT 一: hello-world: #include "mainwindow.h" #include <QApplication> #include < ...
- CF1444D Rectangular Polyline[题解]
Rectangular Polyline 题目大意 给定 \(h\) 条长度分别为 \(l_1,l_2,--,l_h\) 的水平线段以及 \(v\) 条长度分别为 \(p_1,p_2,--.p_v\) ...
- ARC 122 简要题解
ARC 122 简要题解 传送门 A - Many Formulae 考虑对于每个数分别算其贡献. 通过枚举该数前面的符号,借助一个非常简单的 \(\mathrm{DP}\)(\(f_{i,0/1}\ ...
- python根据正则表达式生成指定规律的网址
import os def file_name(file_dir): for root, dirs, files in os.walk(file_dir): print(root) #当前目录路径 p ...
- asp.net web.config数据库连接字符串加密与解密
在WEB网站开发过程中,如果我们将数据库连接字符串封装到.DLL文件中,将会给数据库和程序的迁移带来麻烦,因为万一服务器地址或者数据库发生变更,那么我们就不得不修改源程序并重新将其编译.最好的解决方法 ...
- etcd学习(3)-grpc使用etcd做服务发现
grpc通过etcd实现服务发现 前言 服务注册 服务发现 负载均衡 集中式LB(Proxy Model) 进程内LB(Balancing-aware Client) 独立 LB 进程(Externa ...