python中的typing库
typing的主要作用有:
- 类型检查,防止运行时出现参数、返回值类型不符
- 作为开发文档附加说明,方便使用者调用时传入和返回参数类型
- 模块加入不会影响程序的运行不会报正式的错误,pycharm支持typing检查错误时会出现黄色警告
语法:
1 2 3 4 | def 函数名(参数: 数据类型) - > 返回值类型: pass 变量名: 数据类型 = 值 |
1 2 3 4 5 6 | from typing import Sequence # 这个用来存放一堆定义的类型 from typing import NewType # 用来创建一个新的类型,以便后续可以使用这个来规范类型 |
Any 任意类型
Union[X,Y] 联合类型,X或Y
Option[X] 可选类型,X或None
Tuple[X,Y] 元组类型, 第一个元素X,第二个元素Y,
Callable[[X], Y] 可调用类型,第一个是参数列表,第二个是返回类型
typing包含的类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | AbstractSet = typing.AbstractSet Any = typing. Any AnyStr = ~AnyStr AsyncContextManager = typing.AbstractAsyncContextManager AsyncGenerator = typing.AsyncGenerator AsyncIterable = typing.AsyncIterable AsyncIterator = typing.AsyncIterator Awaitable = typing.Awaitable ByteString = typing.ByteString Callable = typing. Callable ClassVar = typing.ClassVar Collection = typing.Collection Container = typing.Container ContextManager = typing.AbstractContextManager Coroutine = typing.Coroutine Counter = typing.Counter DefaultDict = typing.DefaultDict Deque = typing.Deque Dict = typing. Dict FrozenSet = typing. FrozenSet Generator = typing.Generator Hashable = typing.Hashable ItemsView = typing.ItemsView Iterable = typing.Iterable Iterator = typing.Iterator KeysView = typing.KeysView List = typing. List Mapping = typing.Mapping MappingView = typing.MappingView MutableMapping = typing.MutableMapping MutableSequence = typing.MutableSequence MutableSet = typing.MutableSet NoReturn = typing.NoReturn Optional = typing.Optional Reversible = typing.Reversible Sequence = typing.Sequence Set = typing. Set Sized = typing.Sized TYPE_CHECKING = False Tuple = typing. Tuple Type = typing. Type Union = typing.Union ValuesView = typing.ValuesView |
分类:
python学习笔记
, pytest
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通