IDE 推导 Python 类型

IDE deduce Python type

我正在 Python 中编写一个方法,它看起来像这样:

def rgb_to_grayscale(image):
    print(image.shape)
    pass

此处预期的类型是 numpy.ndarray,它基本上是 OpenCV 中的图像。 IDE 怎么可能预先推断出这个对象的类型,所以我在方法内部得到自动完成?

我正在使用 PyCharm。如果有人知道任何其他 IDE 能够这样做,我愿意接受建议。

您可以在函数签名中添加类型提示

def rgb_to_grayscale(image: numpy.ndarray):
    print(image.shape)
    pass

从 Python 3.5 开始,您可以使用 type hints:

def rgb_to_grayscale(image: numpy.ndarray):

此外,Pycharm 能够通过 defining them in the docstring 识别类型。我更喜欢这个选项,因为它更清晰(在我看来)并且迫使你实际编写一个文档字符串——这对于生产代码(和一般而言)非常重要。你可以这样做:

def rgb_to_grayscale(image):
    """
    :param numpy.ndarray image: the image to be printed
    """
    print(image.shape)

更多方法 Pycharm 可以检测类型,在 this help link

您可以使用:

def rgb_to_grayscale(image: numpy.ndarray):
    print(image.shape)

这适用于所有数据类型。如果将其他值作为参数传递,则会引发 AttributeError