引文与描述:
Adding arbitrary metadata annotations to Python functions and variables
说说我的体会:
类似编译的作用,能够帮助你尽早地避免错误
1. 不支持 Python2+
>>> def test_annotation_py2(a_str: str): File "<stdin>", line 1 def test_annotation_py2(a_str: str): ^ SyntaxError: invalid syntax
2. 代码检查,而且写的时候很容易,并且可以被 IDE 如 Pycharm 支持
3. 基本用法
>>> # all is python built-in type (single) ... def search_for(neddle: str, haystack: str) -> int: ... offset = haystack.find(needle) ... return offset ... >>> # More complicated types ... >>> # Python3.5 added the `typing` module, which both gives us a bunch of new names ... # for types, and tools to build our own types ... >>> from typing import List >>> def multisearch(needle: str, haystack: str) -> List[int]: ... offset = haystack.find(needle) ... if offset == -1: ... return [] ... else: ... return [offset] + multisearch(needle, haystack[offset+1:]) ... >>> # In func multisearch, we define a new type List[int], `List` is from `typeing`, `int` is python built-in type.
# There are many of these -e.g. Dict[keytype, valuetype], if you need more, you can view `typing` documentation ... >>> # A func reteurn different type, use `Union` ... >>> from typing import Union >>> def search_for(needle: str, haystack: str) -> Union[int, None]: ... offset = haystack.find(needle) ... if offset == -1: ... return None ... else: ... return offset
3. 注意事项
# 使用的是 [] 而不是 (): typing.List[] 而不是 typing.List() # 类型混合,比如返回的是 (int, None) 或者是 (int, str),那么可以写为 # typing.Tuple[int, typing.Union[str, None]] 或者 # typing.Union[typing.Tuple[int, str], typing.Tuple[int, None]]
有一个疑问,这样写与静态语言有什么区别?都是在运行前检查。
It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention. Type annotations should not be confused with variable declarations in statically typed languages. The goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools.3
参考: