Python3.5 above version, typing module to improve the robustness of the code

I. Introduction

Python is a weakly typed language, many times we may not know the function argument type or return type is likely to lead to some type of method is not specified, after writing the code for some time back and look at the code, it is possible to forget that he write what functions need to pass parameters, return what type of results, you have to read the specific content of the code, reducing the speed of reading, typing module can solve this problem.

Effect two typing module

  • Type checking, appeared parameters and return values ​​type does not match the run-time.
     
  • Incoming parameters and return types as development documents annotated, user-friendly call.
     
  • After adding the module does not affect the operation of the program, it will not officially reported errors, only a reminder.
Note: typing module can only be used in more than python3.5 version, pycharm currently supports typing inspection

Three common ways typing module

from typing import List, Tuple, Dict

def test(a: int, string: str, f: float, b: bool) -> Tuple[List, Tuple, Dict, bool]:
    ll=[1,2,3,4]
    tup = (string, a, string)
    dic = {"xxx": f}
    boo = b
    return ll, tup, dic, boo

print(test(12, "lqz", 2.3, False))

note:

  • When passing through the parameters: type "parameters type" parameter declaration form;

  • The results returned by - Type "> Result Type" in the form of declaration of results.

  • If the type parameter is incorrect pycharm will be reminded at the time of the call, but will not affect the operation of the program.

  • For lists such as list, provision may also be made more specific number, such as: "-> List [str]", returns a list of predetermined, and the element is a string.

Three common types of typing

  • int, long, float: integer, long integer, floating-point type;

  • bool, str: Boolean type, a string type;

  • List, Tuple, Dict, Set: lists, tuples, dictionaries, collections;

  • Iterable, Iterator: iteration can type, the iterator type;

  • Generator: the type of generator;

Four python inherently support multi-state, the iterator element may be more

from Typing Import List, of Union 

DEF FUNC (A: int, String: STR) -> List [int or STR]: 
    List1 = [] 
    list1.append (A) 
    list1.append (String) 
    return List1 

DEF get_next_id () -> Union [int, None]:
     return 1
     return None
 # use or keyword indicates that a variety of types, you can also use Union

 

Guess you like

Origin www.cnblogs.com/liuqingzheng/p/11012099.html