typing module

typing module

table of Contents

I. Introduction

  • Introduction: Many people after writing the code for some time back and look at the code, it may have forgotten to write their own functions need to pass any parameters, the result of what type of return, you have to read the specific content of the code, reducing the speed of reading , plus Python itself is a weakly typed language, this phenomenon becomes more serious, while typing this module is a good solution to this problem.
    Series of articles

Second, the role of the typing module

  1. Type checking, appeared parameters and return values ​​type does not match the run-time.
  2. Incoming parameters and return types as development documents annotated, user-friendly call.
  3. 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

Third, the use typing module

from typing import List, Tuple, Dict


def add(a: int, string: str, f: float,
        b: bool) -> Tuple[List, Tuple, Dict, bool]:
    list1 = list(range(a))
    tup = (string, string, string)
    d = {"a": f}
    bl = b
    return list1, tup, d, bl


print(add(5, "hhhh", 2.3, False))
([0, 1, 2, 3, 4], ('hhhh', 'hhhh', 'hhhh'), {'a': 2.3}, False)
  • 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.
from typing import List


def func(a: int, string: str) -> List[int or str]:  # 使用or关键字表示多种类型
    list1 = []
    list1.append(a)
    list1.append(string)
    return list1

Four, typing common type

  • int, long, float: integer, long integer, floating point
  • bool, str: Boolean, string type
  • List, Tuple, Dict, Set: lists, tuples, dictionaries, collections
  • Iterable, Iterator: iteration can type, the iterator type
  • Generator: the type of generator

Guess you like

Origin www.cnblogs.com/zhangchaocoming/p/11605907.html