python3 annotations

引文与描述:

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

参考:

1. Python type annotations

2. PEP 3107 -- Function Annotations

3. PEP 526 -- Syntax for Variable Annotations

4. 弱类型、强类型、动态类型、静态类型语言的区别是什么?

转载于:https://www.cnblogs.com/jay54520/p/6432289.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值