VS Code renders markdown fine in mouse hovers - but doesn't render standard docstring formats well

The VS Code Python extension will use markdown that you put into a docstring for intellisense mouse hover information, but this doesn't really meet any of the commonly accepted/used docstring formats for Python. It doesn't properly layout any of those common formats (as of May 2020).

Update (4/2023): Sphinx has been updated to support markdown in docstrings for its auto-code generation, meaning you can put all your docstrings in markdown and they will look good in VS Code hovers and also work with Sphinx

So, your options are:

  1. Stick with one of the major formats that will work with existing Python documentation tools and utilities like Sphinx
  2. Use markdown in your docstrings and look good in VS Code, but be incompatible with most other documentation tools


More Details / Example

The top 3 Python docstring formats are:

  • Google
  • Sphinx
  • NumPY/ReST

VS Code will take ReST format (NumPY style) and properly layout the headers from each section (each item with the line of dashes under it), but in all the formats, the section content is unformatted and munged together with all the linebreaks dropped.

If you use markdown directly in the docstrings, it is supported, but then you aren't meeting the formatting requirements of docstrings for auto documentation frameworks like Sphinx. For example, I started with Sphinx format here and modified it to look better with VS Code's markdown tooltips

def autodoc_test_numpy(self, a: str, b: int = 5, c: Tuple[int, int] = (1, 2)) -> Any:
    """[summary]

    ### Parameters
    1. a : str
        - [description]
    2. *b : int, (default 5)
        - [description]
    3. *c : Tuple[int, int], (default (1, 2))
        - [description]

    ### Returns
    - Any
        - [description]

    Raises
    ------
    - ValueError
        - [description]
    """

Will render like this:

Notice that the final "Raises" section here has the underlining with dashes that makes it a level 1 header (which is the ReST style). Look how big it is! I bumped the other down to h3 by using ### in front of the text instead of underlining it with hyphens on the next line.

Also, note that the type hints in the main function definition (like str in the a: str) render well (even colored) for args and the return type hint, but are not shown for kwargs (e.g. b=5 without the type hint).

Answer from LightCC on Stack Overflow
🌐
GitHub
github.com › microsoft › vscode-python › issues › 1295
Support google-style docstrings for enhanced IntelliSense · Issue #1295 · microsoft/vscode-python
April 4, 2018 - But I'm using google's style of docstring which looks like this · def func(a,b): """ Args: a (int): The first parameter. b (int): The second parameter. Returns: int : return a+b """ return a+b · It seems like vscode can not read param's type from this docstring and give me correct suggestion just like in pycharm. And since vscode-python support sphinx style, it is possible to support google style.
Author: microsoft
Discussions

What is the Python docstring format supported by Visual Studio Code? - Stack Overflow
This also works for the :param username: The name of the user. style and the Google-style Args: list. 2021-08-27T21:42:41.727Z+00:00 ... @arg descr not working in VSCode 1.70.2 + Pylance but :param arg: descr and Args: \n arg: descr did; I chose the latter to avoid repeating param again and ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to use yapf (or black) in VSCode - Stack Overflow
About the yapfArgs, it should be typed like this "python.formatting.yapfArgs": ["--style={based_on_style: pep8, indent_width: 4}"], 2020-04-28T08:42:39.65Z+00:00 ... I agree that the key solution was you needed "editor.formatOnSave": true, but want to point out your question was on using yapf is vscode ... More on stackoverflow.com
🌐 stackoverflow.com
What is the "working" Python docstring style for VS Code tooltips?
I think I see what you mean. It doesn't really answer your question, but here are a couple considerations that can make your life easier in the meantime: I wanted to make the docstrings more legible in the code. I used the extension Highlight to write ugly regexes to match specific characters in a Google-style docstring, to make it more legible, like so . Instead of relying on tooltips, you can rely on another nice feature of VS Code: Peek Definition. It allows you to look to another location in the code in-place. It's a nice way to quickly see what a function does somewhere else in the code. You can bind this operation to a keybind of your liking to do that efficiently. I also recommend using the autoDocstring extension, which works nice. I wrote a custom mustache template to remove types from the Google template, as I rely on the extension sphinx_autodoc_typehints to generate them from my type hints. More on reddit.com
🌐 r/vscode
2
3
March 11, 2020
Which docstring style works best with VS Code?

So Im super interested to see what people say, I would love some other opinions than my own.

I use the autodocstring extension for vscode set to autosetup the docstring template when pressing enter after typing """. Google styling. Gives a template that you can tab through, and can try to guess the types youre using. Its done me pretty well as long as you write the function/the inputs and returns before the docstring setup

Using pylint to scan code for missing docstrings and black/yapf to autoformat the lines that are too long.

More on reddit.com
🌐 r/learnpython
6
13
March 11, 2020
🌐
Google
google.github.io › styleguide › pyguide.html
Google Style Guides | Style guides for Google-originated open-source projects
Python is the main dynamic language used at Google. This style guide is a list of dos and don’ts for Python programs.
Top answer
1 of 4
45

VS Code renders markdown fine in mouse hovers - but doesn't render standard docstring formats well

The VS Code Python extension will use markdown that you put into a docstring for intellisense mouse hover information, but this doesn't really meet any of the commonly accepted/used docstring formats for Python. It doesn't properly layout any of those common formats (as of May 2020).

Update (4/2023): Sphinx has been updated to support markdown in docstrings for its auto-code generation, meaning you can put all your docstrings in markdown and they will look good in VS Code hovers and also work with Sphinx

So, your options are:

  1. Stick with one of the major formats that will work with existing Python documentation tools and utilities like Sphinx
  2. Use markdown in your docstrings and look good in VS Code, but be incompatible with most other documentation tools


More Details / Example

The top 3 Python docstring formats are:

  • Google
  • Sphinx
  • NumPY/ReST

VS Code will take ReST format (NumPY style) and properly layout the headers from each section (each item with the line of dashes under it), but in all the formats, the section content is unformatted and munged together with all the linebreaks dropped.

If you use markdown directly in the docstrings, it is supported, but then you aren't meeting the formatting requirements of docstrings for auto documentation frameworks like Sphinx. For example, I started with Sphinx format here and modified it to look better with VS Code's markdown tooltips

def autodoc_test_numpy(self, a: str, b: int = 5, c: Tuple[int, int] = (1, 2)) -> Any:
    """[summary]

    ### Parameters
    1. a : str
        - [description]
    2. *b : int, (default 5)
        - [description]
    3. *c : Tuple[int, int], (default (1, 2))
        - [description]

    ### Returns
    - Any
        - [description]

    Raises
    ------
    - ValueError
        - [description]
    """

Will render like this:

Notice that the final "Raises" section here has the underlining with dashes that makes it a level 1 header (which is the ReST style). Look how big it is! I bumped the other down to h3 by using ### in front of the text instead of underlining it with hyphens on the next line.

Also, note that the type hints in the main function definition (like str in the a: str) render well (even colored) for args and the return type hint, but are not shown for kwargs (e.g. b=5 without the type hint).

2 of 4
10

As far as I know, there is no official format that is supported. The code has a few functions it runs to convert some parts of RST to Markdown to be displayed, but that is pretty much it.

The code that does the conversion can be found here. The tests, which is a good way of seeing some actual examples, can be found here.

🌐
Medium
medium.com › @lil_johny › ultimate-vs-code-configuration-for-python-programming-2945cdbca5cb
Visual Studio Code configuration for Python programming | by Denys Ivanenko | Medium
July 9, 2019 - This option specifies Python formatting library, that will be used. I prefer yapf because it is developed by Google and can be customized very finely. ”python.formatting.yapfArgs”: [“ — style”,“{based_on_style: pep8, indent_width: 4}”] This option sets formatting style to pep8.
Top answer
1 of 4
39

The problem was in wrong settings. To use yapf, black or autopep8 you need:

  1. Install yapf / black / autopep8 (pip install black)
  2. Configure .vscode/settings.json in the next way:

part of the file:

{
    "python.linting.enabled": true,
    "python.linting.pylintPath": "pylint",
    "editor.formatOnSave": true,
    "python.formatting.provider": "yapf", // or "black" here
    "python.linting.pylintEnabled": true,
}

Key option - "editor.formatOnSave": true, this mean yapf formats your document every time you save it.

2 of 4
20

Extending @Mikhail_Sam answer. You might want to use a separate config file as I like. This way you are decoupling your project settings from VS Code IDE. To do this you need to create .style.yapf:

type null > .style.yapf   (for windows environment)
touch .style.yapf    (for MacOS, Linux environments)

Add rules to .style.yapf, for example:

[style]
based_on_style = google
spaces_before_comment = 4
indent_width: 2
split_before_logical_operator = true
column_limit = 80

Don't forget to remove from your VS code settings.json the following setting. They override .style.yapf:

"python.formatting.yapfArgs": [
  "--style={based_on_style: google, column_limit: 80, indent_width: 2}"
],

My other VS Code settings in settings.json:

"[python]": {
  "editor.defaultFormatter": "ms-python.python",
  "editor.formatOnSave": true
},
"python.formatting.provider": "yapf",
"python.formatting.yapfPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\yapf.exe",
"python.formatting.blackPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\black.exe",
"python.linting.lintOnSave": true,
"python.linting.enabled": true,
"python.linting.pylintPath": "pylint",
"python.linting.pylintEnabled": true,

According to the YAPF documentation: YAPF will search for the formatting style in the following manner:

  1. Specified on the command line >> VS Code settings.json
  2. In the [style] section of a .style.yapf file in either the current directory or one of its parent directories.
  3. In the [yapf] section of a setup.cfg file in either the current directory or one of its parent directories.
  4. In the [style] section of a ~/.config/yapf/style file in your home directory.
  5. If none of those files are found, the default style is used (PEP8).
🌐
minkj1992
minkj1992.github.io › python_formatter
Google like python on vscode | minkj1992
April 19, 2022 - Describes python google style editor settings on vscode
Find elsewhere
🌐
Reddit
reddit.com › r/vscode › what is the "working" python docstring style for vs code tooltips?
r/vscode on Reddit: What is the "working" Python docstring style for VS Code tooltips?
March 11, 2020 -

AFAIK I know, there are three major docstring conventions beyond PEP 257:

  • reST style

  • Google style

  • NumPy style

I use Google style because I find it the simplest. I'm also using type hints throughout my code, which helps keep docstrings readable and concise.

Unfortunately, VS Code's tooltips provide no proper support for any of them. It tries to parse the entire docstring as Markdown, resulting in ugly or illegible tootltips. I recently disabled Jedi in favor of MS Language Server which made the problem worse. (Notes on this below)

I could ditch all docstring conventions and resort to writing Markdown, but it would mean giving up my documentation generation tools (sphinx, pydocmd). Has anyone managed to get docstring tooltips to look good on VS Code?

Sidetrack: Jedi vs MS Language Server?

Note: I disabled Jedi because it wanted to use rope for renaming variables. For some reason, VS Code fails to rename variables even when I install rope in my venv. In contrast, refactoring with MS Language Server just works...though it breaks tooltips even more.

So I am stuck in a dilemma between Jedi & MSLS:

  • Subpar tooltips & no refactoring support, or

  • Even worse tooltips & refactoring support

BTW, I'm using VS Code on Windows 10 with Git Bash as the default terminal. This setup allows me to use Linux commands provided by Git Bash, but has been causing some headaches...

Edit: I just checked again, and reStructuredText actually seems to produce somewhat usable docstrings. The caveat being that there is no way to document class attributes directly (Google style has the Attributes: section).

Top answer
1 of 2
1
I think I see what you mean. It doesn't really answer your question, but here are a couple considerations that can make your life easier in the meantime: I wanted to make the docstrings more legible in the code. I used the extension Highlight to write ugly regexes to match specific characters in a Google-style docstring, to make it more legible, like so . Instead of relying on tooltips, you can rely on another nice feature of VS Code: Peek Definition. It allows you to look to another location in the code in-place. It's a nice way to quickly see what a function does somewhere else in the code. You can bind this operation to a keybind of your liking to do that efficiently. I also recommend using the autoDocstring extension, which works nice. I wrote a custom mustache template to remove types from the Google template, as I rely on the extension sphinx_autodoc_typehints to generate them from my type hints.
2 of 2
1
Coming from TypeScript hurts to have such ugly docs :-P. This was the best custom format I could come up with, which has the advantage of technically being valid yaml so it should be fairly straight forward to parse if needed. https://imgur.com/a/5lgkiYi https://user-images.githubusercontent.com/15365418/89723797-e52f7280-d9c8-11ea-8b6a-9362319e0cea.png class RestResponseExchange(TypedDict): """ Returns basic information about the exchange. ### References - https://docs.idex.io/#get-exchange ### Attributes `timeZone: str`: summary: 'Timezone pass of the exchange' example: 'UTC' `serverTime: int`: summary: 'Current server timestamp in milliseconds' example: 1596938576511
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › formatting
Formatting | Python in Visual Studio Code
"python.formatting.yapfArgs": ["--style", "{based_on_style: chromium, indent_width: 20}"] pip install yapf · Topics: Python Path and Version · Autocomplete · Formatting · Linting · Debugging · -> Terminal (Console) Apps · -> Capture User Input · -> Library Functions · -> Google App Engine ·
🌐
Medium
medium.com › little-big-engineering › use-visual-studio-code-for-python-development-5d59c8479add
Use Visual Studio Code for Python Development | by Jie Feng | Little Big Engineering | Medium
May 2, 2018 - This post is to introduce my easy setup to work on Python using VSCode (assume you are on Mac or Linux, Windows should be fairly similar). ... Open ~/.pylintrc and update tab size to 2 (Google style, making file more compact; if you stick with default PEP8, skip this):
🌐
Visual Studio Code
code.visualstudio.com › docs › python › editing
Editing Python in Visual Studio Code
November 3, 2021 - To enable IntelliSense for packages that are installed in non-standard locations, add those locations to the python.analysis.extraPaths collection in your settings.json file (the default collection is empty). For example, you might have Google App Engine installed in custom locations, specified in app.yaml if you use Flask.
🌐
Reddit
reddit.com › r/learnpython › which docstring style works best with vs code?
r/learnpython on Reddit: Which docstring style works best with VS Code?
March 11, 2020 -

AFAIK I know, there are three major docstring conventions beyond PEP 257:

  • reST style

  • Google style

  • NumPy style

I use Google style because I find it the simplest. I'm also using type hints throughout my code, which helps keep docstrings readable and concise.

Unfortunately, VS Code's tooltips provide no proper support for any of them. It tries to parse the entire docstring as Markdown, resulting in ugly or illegible tootltips. I recently disabled Jedi in favor of MS Language Server which made the problem worse. (Notes on this below)

I could ditch all docstring conventions and resort to writing Markdown, but it would mean giving up my documentation generation tools (sphinx, pydocmd). Has anyone managed to get docstring tooltips to look good on VS Code?

Sidetrack: Jedi vs MS Language Server?

Note: I disabled Jedi because it wanted to use rope for renaming variables. For some reason, VS Code fails to rename variables even when I install rope in my venv. In contrast, refactoring with MS Language Server just works...though it breaks tooltips even more.

So I am stuck in a dilemma between Jedi & MSLS:

  • Subpar tooltips & no refactoring support, or

  • Even worse tooltips & refactoring support

BTW, I'm using VS Code on Windows 10 with Git Bash as the default terminal. This setup allows me to use Linux commands provided by Git Bash, but has been causing some headaches...

Edit: I just checked again, and reStructuredText actually seems to produce somewhat usable docstrings. The caveat being that there is no way to document class attributes directly (Google style has the Attributes: section).

🌐
Medium
victorleungtw.medium.com › visual-studio-code-with-python-auto-formatting-8ba92b44360
Visual Studio Code with Python auto-formatting | by Victor Leung | Medium
December 8, 2020 - "python.formatting.yapfArgs": [ "--style", ".style.yapf" ] Now you can test it out, such as not having a new line at the end of the python file, then press saves, it would fix your new line issue automatically for you. Written by Victor Leung who is a keen traveller to see every country in the world, passionate about cutting edge technologies. Get in touch · Originally published at https://victorleungtw.com. Python · Vscode ·
🌐
Stack Overflow
stackoverflow.com › questions › tagged › google-style-guide
Newest 'google-style-guide' Questions - Stack Overflow
I am trying to use the google-style directive with pdoc, but it doesn't work on my side. Where am I wrong? Below is my code. Please help me. :) def save(a: str, b:str) -> set: "&... ... Google Python Style Guide says: Do not use relative names in imports. Even if the module is in the same package, use the full package name.
🌐
Reddit
reddit.com › r/learnpython › style guides for python
r/learnpython on Reddit: Style Guides for Python
March 18, 2020 -

After some other people pointed out on my previous post that I was lacking a style guide for my code, I wanted to look into making my code more user friendly. I tried following along with the PEP 8 style guide on the python website, but I don’t feel like I am retaining any of the info. Would you be able to help me figure out ways to improve the style and redundancy of my code. Thank you

🌐
HackerNoon
hackernoon.com › how-googles-python-code-style-guide-can-help-you-speed-your-engineering-team
How Google’s Python Code Style Guide Can Help You Speed Your Engineering Team | HackerNoon
July 15, 2022 - Broadly speaking the Language Rules are used to define how Google approaches using (and importantly not using) and structuring different elements of the Python language within their code. This is a critically important aspect of a Style Guide for teams that have different levels of experience in a given language because it helps provide guide rails around the code structure and on what type of advanced language feature your team should and shouldn’t use.
🌐
Visual Studio Code
code.visualstudio.com › docs › python › linting
Linting Python in Visual Studio Code
November 3, 2021 - Linting highlights semantic and stylistic problems in your Python source code, which often helps you identify and correct subtle programming errors or coding practices that can lead to errors.
🌐
DEV Community
dev.to › adamlombard › how-to-use-the-black-python-code-formatter-in-vscode-3lo0
VSCode: Using Black to automatically format Python - DEV Community
April 4, 2024 - Open your VSCode settings, by going 'Code -> Preferences -> Settings'. Search for "python formatting provider" and select "black" from the dropdown menu:
🌐
Sourcery
sourcery.ai › blog › google-python-style-guide
Introducing the Google Python Style Guide in Sourcery
September 14, 2022 - We previously broke down the different elements of the Google Python Style Guide and talked about why they are useful rules to have in your Python projects.