前言

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 模块 —— 常用类型提示的更多相关文章

  1. Python - typing 模块 —— 类型别名

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  2. Python - typing 模块 —— NewType

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  3. Python - typing 模块 —— Callable

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  4. Python - typing 模块 —— TypeVar 泛型

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  5. Python - typing 模块 —— Any Type

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  6. Python - typing 模块 —— Union

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  7. Python - typing 模块 —— Optional

    前言 typing 是在 python 3.5 才有的模块 前置学习 Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html 常用类型提示 ...

  8. Python OS模块常用功能 中文图文详解

    一.Python OS模块介绍 OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. 可以查看OS模块的帮助文档: >>> i ...

  9. Python Type Hints(类型提示)

    在做自动化测试的时候,改进测试框架,类型提示会让你写代码时更加流程,当你在一个模块定义了类型,而其他模块没有提示的时候,是相当不方便.

随机推荐

  1. TCP/UDP/HTTP的区别和联系(转载)

    一.TPC/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据. 关于TCP/IP和HTTP协议的关系,网络有一段比较容易理解的介绍:"我们在传 ...

  2. python找出字典中value最大值的几种方法

    假设定义一字典,m = {"a":3,"e":6,"b":2,"g":7,"f":7,"c ...

  3. python02篇 字典、元组、切片

    一.字典 1.1 字典的常用方法 # 字典 数据类型 {} key-value # list是挨个循环查找,字典是根据key查找value,比list遍历效率高 d = { 'username': ' ...

  4. CTF-Streamgame1-writeup

    Streamgame1 题目信息: 附件: streamgame1.py from flag import flag assert flag.startswith("flag{") ...

  5. C语言:异或

    异或运算符"∧"也称XOR运算符.它的规则是若参加运算的两个二进位同号,则结果为0(假):异号则为1(真).即 0∧0=0,0∧1=1, 1^0=1,1∧1=0. 相同为0,不相同 ...

  6. 单机版kafka的安装

    简单记录单机版kafka的安装:JDK1.8(jdk-8u131-linux-x64.rpm)zookeeper (zookeeper-3.4.10.tar.gz)kafka (kafka_2.12- ...

  7. Requests方法 -- Http协议的短链接与长连接介绍

    转载于简书: 作者:熊师傅链接:https://www.jianshu.com/p/3fc3646fad80 1.以前的误解 很久之前就听说过长连接的说法,而且还知道HTTP1.0协议不支持长连接,从 ...

  8. ThinkPHP5修改验证码的配置参数

    当前使用的ThinkPHP的版本是5.0.24. 在模版试图中调用验证码生成函数:{:captcha_img()},或者<img src="{:captcha_src()}" ...

  9. 使用Angular CDK实现一个Service弹出Toast组件

    在Angular中,官方团队在开发Material组件库的同时,顺手做了一套Component dev kit,也就是在Angular世界中大名鼎鼎的CDK,这套工具包提供了非常多的前端开发的通用功能 ...

  10. sqldbx配置连接Oracle 12C数据库

    本地开发环境: Windows10 64位.Oracle 12C客户端 32位.sqlDBX (32位) =============================================== ...