Steve
Steve

Reputation: 4975

VSCode auto complete string params for python

I've been looking around to see if I can create the same behaviour for Python in VSCode to show string param inputs as you can do with jsdoc in JavaScript.

JavaScript example with JSDoc:

/**
* @method someMethod
* @description A special method.
* @param { "option1" | "option2" } param1 Choose an option.
*/
function someMethod(param1) {
    console.log(param1);
}

So when calling the method, VSCode will give auto completion options for param1.

enter image description here

So I'm looking for a Python equivalent, preferably using google docstring format:

def some_method(param1: str) -> None:
    """A special method.

    Args:
        param1 (str): Choose an option. # HOW CAN WE ADD INTELLISENSE OPTIONS HERE??
    
    """
    print(param1)

Upvotes: 5

Views: 3717

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121774

In VSCode, it is the language server used that determines autocompletion. The current 'gold standard' for Python completion is the Microsoft Pylance extension, which builds on Microsoft Pyright to analyse your source code.

Pyright, in turn, relies on type inference and type hints to understand what autocompletion options you have available. While this does include support for comments, there is no support for type hints in docstrings (this was explicitly rejected in the type hinting spec).

If you are used to Typescript, Python type hints and Pylance should work in pretty much the same way. Your own example already includes type hints, and the literal translation of your example would be to use literal types:

from typing import Literal

def some_method(param1: Literal["option1", "option2"]) -> None:
    """A special method."""
    print(param1)```

You can then auto-complete on those values:

Visual Studio screenshot with Intellisense autocompletion offering 'option1' and 'option2' strings.

Upvotes: 7

Related Questions