Search code examples
pythonpycharmpython-typing

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

  • 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