Python3.5 中新增了一个功能是类型提示(type hints) - PEP 484 -- Type Hints. 其作用是,提高代码可读性,指明传入参数和返回数据的类型,有助于理解函数的输入输出.

  • 冒号后面是建议传入的参数类型
  • 箭头后面是建议函数返回的类型

如:

def greeting(name: str) -> str: return 'Hello ' + name

该代码块指明了,输入参数 name 为 str 类型;且该函数的输出结果也为 str 类型.

注:类型提示并非强制规定和检查,即,即使传入的实际参数与建议参数不符,也不会报错. 如:

def value_sum(a: int, b: int=100) -> int: sum = a + b return sum # print(value_sum(1, 2)) # out: 3 print(value_sum('1', '2')) # out: '12'

1. codeblock

From: facebook - detectron2/structures/mask.py

import numpy as np import pycocotools.mask as mask_utils from typing import List def polygons_to_bitmask( polygons: List[np.ndarray], height: int, width: int) -> np.ndarray: """ Args: polygons (list[ndarray]): each array has shape (Nx2,) height, width (int) Returns: ndarray: a bool mask of shape (height, width) """ assert len(polygons) > 0, "COCOAPI does not support empty polygons" rles = mask_utils.frPyObjects(polygons, height, width) rle = mask_utils.merge(rles) return mask_utils.decode(rle).astype(np.bool)

2. 参考

[1] - PEP 484 -- Type Hints

[2] - 【python3】参数中的冒号与箭头

[3] - Python函数参数中的冒号与箭头

Last modification:June 22nd, 2020 at 10:23 am