Making Suggestions to Python Intellisense

Usually intellisense works for your code, unless it doesn’t.

When doesn’t intellisense work?

Since Python is a dynamically typed language, it is not always possible to accurately determine the data type in some scenarios.

Consider below code:

def get_random(type):
    if type == 'str':
        return 'hello'
    else:
        return 1
 data = get_random('str')

What does the ‘get_random’ function return - a string or an Integer? The answer is, it depends.

Making Suggestions to Intellisense

Is there a way to still make intellisense show up, even when it doesn’t? Yes, you can.

Say you have an Python function/API which has some complex logic due to which the return type of the function is not correctly determined by the IDE. In this case, you can specify the return data type of the function to make suggestions to the IDE’s Intellisense.

For example:

class parent():
    def func_1(self):
        return 1

    def func_2(self):
        return 2

def get_random()->parent:
    return 1

data = get_random()

Here you are explicitly stating to the IDE that the return type of the function is of type ‘parent’ class. Due to this, intellisense would make suggestions assuming this to be true.

What about outside functions?

If you are certain on what is the expected data type (say a class), you can use assert statement to verify your assumption and at the same time, tell the IDE that this variable would definitely be of this type.

For easier understanding, let me show you an example which is not expected to work:

class parent():
    def func_1(self):
        return 1

    def func_2(self):
        return 2

class child():
    def get():
        return child()

my_child = child()

assert isinstance(my_child, parent)
# Now intellisense for 'my_child' would list func_1 and func_2.

In this way, you can even make intellisense to show up even it is not able to automatically do so.

No comments:

Feel free to leave a piece of your mind.

Powered by Blogger.