Answer a question

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)

Answers

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.

(I note that there appears to be a bug in the current VSCode or Pylance release where I can only autocomplete the string by placing my cursor after the closing quote; I'm sure this'll be fixed in a future release).

One caveat: Pylance is still marked as a preview project. It is improving very fast, however, and I use it in all my Python work.

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐