前言
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
Union
https://www.cnblogs.com/poloyy/p/15170066.html
Optional
https://www.cnblogs.com/poloyy/p/15170297.html