Python type hints 调研
参考链接:
官网 https://docs.python.org/3/library/typing.html
https://ocavue.com/python_typing.html
https://blog.youkuaiyun.com/chuchus/article/details/77891128
https://www.cnblogs.com/erhuabushuo/p/10180789.html
1.function annotation
def plus(a: int, b: int = 2) -> int: return a + b
这个暂且翻译为函数注解,从python3.0 (见 PEP3107)。Python 解释器在运行时并不会检查类型,所以哪怕参数的类型不对,Python 解释器也不会因此抛出任何异常。
2.Python 3.5: typing
1.typing的基础类型
from typing import Dict, List
def best_students(scores: Dict[str, int]):
return {name: score for name, score in scores.items if score >= 90}
Dict[str, int]表示一个 keys 的类型为 str,values 的类型为 int 的字典,比如{"a": 1, "b": 2}。
List[int]表示由整型组成的列表,比如[0, 1, 1, 2, 3]。
Tuple[str, int] 表示一个元组有两个元素,第一个元素是str类型,第二个是int类型。
基于 typing 提供的类型,我们可以写出相当复杂的嵌套结构:
Dict[str, Dict[str, List[str]]]
{
'原木镇': {
'第一小学': ['张伟', '王伟', '王芳'],
'第二小学': ['李伟', '李娜'],
},
'鸽子镇': {
'高山中学': ['张敏', '李静'],
'亿百中学': ['王静']
'蟒蛇小学': ['刘伟', '王秀英']
}
}
2.typing的高级类型
a. Union[None, str] 表示None或者str,下面的函数返回None类型,或者str类型
from typing import Union, List def get_first_name(names: List[str]) -> Union[None, str]: if len(names) >= 1: return names[0] else: return None
b. Callable[[str, str], bool] 表示一个函数,接收两个str类型的位置参数,返回值是bool类型
from typing import Callable def get_regex() -> Callable[[str, str], bool]: def regex(pattern: str, string: str) -> bool: return re return regex()
c. 泛型(Generics)
在python中除了基本数据类型(列表、元组等),由基本数据类型复合构成的数据类型(序列、映射、容器、迭代器等)称为复合数据类型。
复合类型这里称为泛型(Generics), 在.typing中有对应的类与其对应。
from typing import Mapping, Sequence def notify_by_email(employees: Sequence[Employee], overrides: Mapping[str, str]) -> None: pass
Sequence[Employee] 表示一个序列,序列中的元素为Employee类型。
Mapping[str, str] 表示一个映射,映射的键为str类型,值为str类型。
TypeVar 用来注解可变类型的变量、参数,可以通过typing中的TypeVar来注解泛型中的元素下标。
from typing import Sequence, TypeVar
T = TypeVar('T') # 申明类型变量
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
TypeVar声明类型变量时,可以提供一个范围:
T = TypeVar('T') # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
d. Any,任何类型
from typing import Any def log(msg: Any): print(Any)
3.Python 3.6: variable annotations
变量注解
items: list = read_json_file() class Employee(NamedTuple): name: str id: int = 3
4. __annotations__ 属性保存类型注解
>>> def foo(a: str):
... print('hello', a)
...
>>> foo.__annotations__
{'a': str}
>>> class Bar:
... a: str
... b: int
>>> Bar.__annotations__
{'a': str, 'b': int}
5. python typing 做不到的地方
a. 关键字传参
def foo(item: str) -> None: print(item + "s") foo(item=0)
b. 装饰器修饰的函数
Python type hints 调研
本文对 Python type hints 进行调研,介绍了从 Python 3.0 开始的 function annotation,Python 3.5 的 typing 基础类型、高级类型,Python 3.6 的 variable annotations,还提及属性保存类型注解以及 python typing 做不到的地方,如关键字传参、装饰器修饰的函数等。
692

被折叠的 条评论
为什么被折叠?



