typing使用
官方文档: typing
注: typing是python3.5(PEP484)开始的
可用于: 类型检查器、集成开发环境、静态检查器等, 但是不强制使用
使用方式
两种使用方式
- 别名: 先定义
=, 再使用:- 直接使用:
:
from typing import List
T1 = List[str]
def test(t1: T1, t2: List[str]):
print(t1[0].title())
print(t2[0].title())
创建新类型 NewType
主要用于类型检测
NewType(name, tp)返回其原本的值
静态类型检查器会将新类型看作是原始类型的一个子类
即:name是新的类型tp是原始类型
注: 在python3.10之前NewType是普通的函数, 之后是一个类, 会产生一个类, 返回的原来的值, 故不会对常规函数产生影响
from typing import NewType, NoReturn
# 创建int的子类, 名为UserId
UserIdType = NewType('UserId', int)
# 使用
def name_by_id(user_id: UserIdType) -> NoReturn:
print(user_id)
# 类型检测错误
UserIdType('user')
# 类型检测成功, 返回原类型 "int"
num = UserIdType(5)
# 类型检测错误, 需要传入UserIdType, 而不是int
name_by_id(42)
# 类型检测成功
name_by_id(UserIdType(42)) # OK
类型变量 TypeVar
类型变量主要用于泛型类型与泛型函数定义的参数
第一个参数是名称, 其他参数是类型
from typing import TypeVar, Sequence
# 任意类型
T = TypeVar('T')
# 必须是str或bytes
A = TypeVar('A', str, bytes)
# (any, int) -> [any, ...]
def repeat(x: T, n: int) -> Sequence[T]:
return [x] * n
# (str/bytes, str/bytes) -> str/bytes
def longest(x: A, y: A) -> A:
return x if len(x) >= len(y) else y
元祖 Tuple
使用场景
- 有限元素:
Tuple[X, Y], 即第一个元素类型为X, 第二个元素类型为Y- 空元组:
Tuple[()]- 可用
...指定任意个同类:Tuple[int, ...]即多个int元素的元组- 不指定时(
Tuple)等价于Tuple[Any, ...]
from typing import Tuple
# 任意类型元组
def t1(t: Tuple):
pass
# 全为字符串的元组
def t2(t: Tuple[str, ...]):
pass
# 多个类型有 "..." 时为任意类型
def t3(t: Tuple[str, int, ...]):
pass
列表 List
使用方式如上的Tuple
from typing import List
# 任意类型
def t1(t: List):
pass
# 全为字符串
def t2(t: List[str, ...]):
pass
# 多个类型有 "..." 时为任意类型
def t3(t: List[str, int, ...]):
pass
字典 Dict
定义形式:
Dict[key类型, val类型]
from typing import Dict
# key为字符串 value为int
def t1(t: Dict[str, int]):
pass
集合 Set
不能使用
...
最多只能有一个参数, 即只能有一种类型
from typing import Set
# 任意类型
def t1(t: Set):
pass
# 字符串
def t2(t: Set[str]):
pass
序列类型 Sequence
使用注意点与Set相同
from typing import Union, Sequence
# int
def t1(t: Sequence[int]):
pass
可调用类型 Callable
即可调用对象
定义形如:Callable[[Arg1Type, Arg2Type], ReturnType], 第一个参数是列表 值为可调用对象的参数类型, 第二个参数是返回值
from typing import Callable
def test(c: Callable[[int, str], str]):
res = c(1, "a")
# 1a <class 'str'>
print(res, type(res))
def func(a: int, b: str) -> str:
return str(a) + b
test(func)
任意类型 Any
任意类型
from typing import Any
# 任意类型
def t1(a: Any, b: ...):
pass
t1(1, 2)
t1("a", "b")
无返回值 NoReturn
标记没有返回值的函数
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
联合类型 Union
即必须是指定的类型
联合中的联合会被展平:
Union[Union[int, str], float] == Union[int, str, float]
单参数即本身:Union[int] == int
冗余参数跳过:Union[int, str, int] == Union[int, str] == int | str
无顺序:Union[int, str] == Union[str, int]
from typing import Union
# str或int
def t1(t: Union[str, int]):
pass
python3.10之后可以写成
X | Y, 不需要额外导入Union
可选类型 Optional
即可以是指定的类型
含默认值的可选参数不需要在类型注解上添加 Optional 限定符
默认值为None时, 可以用Optional
from typing import Optional
# t的类型可以是int
def t1(t: Optional[int] = None):
pass
typing使用的更多相关文章
- Python标准库--typing
作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 1 模块简介 Python 3.5 增加了一个有意思的库--typ ...
- 最牛的打字效果JS插件 typing.js
最新在做公司的一个项目,需要实现一个敲打代码的动画效果,粗意味比较简单,果断自己直接开写,写着写着发现是一个坑.需要支持语法高亮,并不能直接简单的用setTimeout来动态附件innerHTML.苦 ...
- Monkey Patch/Monkey Testing/Duck Typing/Duck Test
Monkey Patch Monkey Testing Duck Typing Duck Test
- SGU 422 Fast Typing(概率DP)
题目大意 某人在打字机上打一个字符串,给出了他打每个字符出错的概率 q[i]. 打一个字符需要单位1的时间,删除一个字符也需要单位1的时间.在任意时刻,他可以花 t 的时间检查整个打出来的字符串,并且 ...
- Cellphone Typing 字典树
Cellphone Typing Time Limit: 5000ms Memory Limit: 131072KB This problem will be judged on UVA. Ori ...
- 什么是“鸭子类型(duck typing)”?
在计算机编程世界里会接触到一个知识点 —— duck typing,叫“鸭子类型”. 它有一个形象的解释: “当看到一只鸟走起来像鸭子.游泳起来像鸭子.叫起来也像鸭子,那么这只鸟就可以被称为鸭子. ...
- thinking in java Generics Latent typing
The beginning of this chapter introduced the idea of writing code that can be applied as generally a ...
- 鸭子类型duck typing(动态)
在程序设计中,鸭子类型(duck typing)是动态类型的一种风格.在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由当前方法和属性的集合决定.这个概念的名字来源于由Ja ...
- How to Avoid Producing Legacy Code at the Speed of Typing
英语不好翻译很烂.英语好的去看原文. About the Author I am a software architect/developer/programmer.I have a rather p ...
- 使用python3的typing模块提高代码健壮性
前言:很多人在写完代码一段时间后回过头看代码,很可能忘记了自己写的函数需要传什么参数,返回什么类型的结果,就不得不去阅读代码的具体内容,降低了阅读的速度,加上Python本身就是一门弱类型的语言,这种 ...
随机推荐
- 转载 使用wce进行本地和域的hash注入
参数解释:-l 列出登录的会话和NTLM凭据(默认值)-s 修改当前登录会话的NTLM凭据 参数:<用户名>:<域名>:<LM哈希>:<NT哈希>-r ...
- 关于国密HTTPS 的那些事(二)
关于国密HTTPS 的那些事(二) 三. 需要解决的问题 前文我们了解了https,并梳理了国密https的流程.那么完成这些流程的目的是什么呢?又是怎么来保护数据的安全性呢?我们继续... 上文我们 ...
- PLSQL安装,PLSQL汉化,激活
一)准备工作 1.点击下载PLSQL:https://www.allroundautomations.com/registered-plsqldev/.本次安装的是12.0.7,安装版本为64位 2. ...
- Conversion Tools(转换工具)
转换工具 1.Excel # Process: Excel 转表 arcpy.ExcelToTable_conversion("", 输出表, "") # Pr ...
- 通过ideviceinstaller获取IOS APP bundleId
查看ios设备udid: idevice_id -l 查看ios应用的bundleId: # 安装ideviceinstaller brew install ideviceinstaller # 查看 ...
- python字符串调用举例
以如下打印为例: my name is tom and my age is 12 方式一:字符串格式化表达式 name = 'tom' age = 12 print("my name is ...
- window系统上实现mongodb副本集的搭建
一.问题引出 假设我们生产上的mongodb是单实例在跑,如果此时发生网络发生问题或服务器上的硬盘发生了损坏,那么这个时候我们的mongodb就使用不了.此时我们就需要我们的mongodb实现高可用, ...
- 同人逼死官方系列!基于sddc 协议的SDK框架 sddc_sdk_lib 解析
基于sddc 协议的SDK框架 sddc_sdk_lib 解析 之前在移植 libsddc 库的时候感觉官方 demo 太低效了( ̄. ̄),复制粘贴代码好累,而且写出一个BUG,其他复制的代码整个就裂 ...
- 0x02
#include<bits/stdc++.h> using namespace std; int n,a[10][10],vis[10],ans,b[10][10]; inline int ...
- Linux的inode与block
1,inode包含文件的元信息,具体来说有以下内容: 文件的字节数 文件拥有者的User ID 文件的Group ID 文件的读.写.执行权限 文件的时间戳,共有三个:ctime指inode上次文件属 ...