首页 > 编程语言 > 详细

python3 annotations

时间:2017-02-23 11:56:59      阅读:201      评论:0      收藏:0      [点我收藏+]

引文与描述:

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

有一个疑问,这样写与静态语言有什么区别?都是在运行前检查。

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. 弱类型、强类型、动态类型、静态类型语言的区别是什么?

python3 annotations

原文:http://www.cnblogs.com/jay54520/p/6432289.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!