[ ]
ZhouSa.com-周飒博客 1. *类型注释和检验
python3.5起就支持函数的类型注释(pep 484),它的结构如下:
def func(arg:int)->int: pass
ps:类型注释只是注释,python解释器并不会处理它,要让它有类型检验的功能还要有其他工具配合.
函数的参数类型保存在它的__annotations__
属性上
func.__annotations__
{'arg': int, 'return': int}
1.1. *自定义泛型注解
类型注释可以直接使用系统自带的类和自己定义的类,但对于泛型注解就力不从心了,对于这种需求,python内置了typing模块来帮助泛型注释
1.1.1. 协程注释
async def spam(ignored: int) -> str: return 'spam' async def foo() -> None: bar = await spam(42) # type: str
1.1.2. 类型别名
Url = str def retry(url: Url, retry_count: int) -> None: pass
1.1.3. 可调用类型
from typing import Callable def feeder(get_next_item: Callable[[], str]) -> None: pass def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: pass
1.1.4. 生成器类型
from typing import Generator def echo_round() -> Generator[int, float, str]: res = yield while res: res = yield round(res) return 'OK'
from typing import Mapping, Set def notify_by_email(employees: Set[int], overrides: Mapping[str, str]) -> None: pass
1.1.5. 泛型
from typing import Sequence, TypeVar T = TypeVar('T') # Declare type variable def first(l: Sequence[T]) -> T: # Generic function return l[0]
1.1.6. 受限泛型
from typing import TypeVar AnyStr = TypeVar('AnyStr', str, bytes)#必须是str或者bytes def concat(x: AnyStr, y: AnyStr) -> AnyStr: return x + y
1.1.7. Union类型
Union类型常用于可选类型
func.__annotations__
0
1.1.8. Optional类型
Optional类型通常表示这个被注释的参数是可以为None的.
func.__annotations__
1
1.1.9. 用户自定义泛型
func.__annotations__
2
1.1.10. any类型
any类型和ts中一样,代表任意类型都可以
1.1.11. 方法重载
func.__annotations__
3
1.1.12. 变量注解[3.6]
3.6版本起变量类型也可以注释了(pep 526),这看起来就像c语言一样,然而它依然还是注释
func.__annotations__
4
func.__annotations__
5
模块,类中的的变量注解同样保存在__annotations__
中
func.__annotations__
6
func.__annotations__
7
func.__annotations__
8
func.__annotations__
9
func.__annotations__
7
{'arg': int, 'return': int}
1
{'arg': int, 'return': int}
2
1.2. 静态类型检验
python解释器并不会做静态类型检验,我们可以利用mypy来实现
{'arg': int, 'return': int}
3
{'arg': int, 'return': int}
4
{'arg': int, 'return': int}
5
{'arg': int, 'return': int}
6
1.3. *运行时类型检测
标准库自带的typing只能用于静态检测,当我们需要运行时检测时可以借助enforce来实现.enforce使用装饰器语法, 它提供了装饰器 @runtime_validation
用于运行时进行类型检测.同时提供了工具is_type_of_type
来对类型和申明类型进行比较.
需要注意的是is_type_of_type
对通过cloudpickle的对象无效
{'arg': int, 'return': int}
7
{'arg': int, 'return': int}
8
{'arg': int, 'return': int}
9
async def spam(ignored: int) -> str: return 'spam' async def foo() -> None: bar = await spam(42) # type: str
0
async def spam(ignored: int) -> str: return 'spam' async def foo() -> None: bar = await spam(42) # type: str
1
async def spam(ignored: int) -> str: return 'spam' async def foo() -> None: bar = await spam(42) # type: str
2
还没有评论,来说两句吧...