zoukankan      html  css  js  c++  java
  • 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. 弱类型、强类型、动态类型、静态类型语言的区别是什么?

  • 相关阅读:
    day6_redis模块和pipeline
    day6_hashlib模块
    18 MySQL数据导入导出方法与工具介绍之二
    【Vijos1264】神秘的咒语
    【Vijos1180】选课
    【vijos1234】口袋的天空
    【vijos1790】拓扑编号
    【WC2008】【BZOJ1271】秦腾与教学评估(二分,前缀和,奇偶性乱搞)
    【Baltic2003】【BZOJ1370】Gang团伙(并查集,拆点)
    【基础】二分算法学习笔记
  • 原文地址:https://www.cnblogs.com/jay54520/p/6432289.html
Copyright © 2011-2022 走看看