'IDE deduce Python type

I am writing a method in Python, which looks something like this:

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

The one expected type here is numpy.ndarray, which is basically an image in OpenCV. How is it possible for the IDE to deduce the type of this object beforehand, so I get autocompletion inside the method?

I am using PyCharm. If anyone knows any other IDE which is capable to do so, I am open to suggestions.



Solution 1:[1]

Since Python 3.5, you can use type hints:

def rgb_to_grayscale(image: numpy.ndarray):

Also, Pycharm is capable of recognizing types by defining them in the docstring. I prefer this option as it is more clear (in my opinion) and forces you to actually write a docstring - which is very important for production code (and in general). You could do something like:

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

More ways Pycharm can detect types, in this help link

Solution 2:[2]

You can add type hint to the function signature

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

Solution 3:[3]

You can use :

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

This is applicable to all data types. If some other value is passed as an argument then it will raise a AttributeError

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Guy
Solution 3