4

I write code in Python in VS code. If I add comment before function and hit save button, VS code adds two empty lines:

# comment


def MyMethod():
    return 0

In settings I see that I use autopep8 formatter: autopep8 formatter

I wasnt able to find what causes this annoying issue. Maybe I can configure settings somewhere?

vytaute
  • 1,260
  • 4
  • 16
  • 36
  • 1
    You could use something like autopep8 or black? Usually, vscode asks you about the formatter you'd like to use, you can use wither of auto pep8 or black – Amartya Gaur Oct 24 '21 at 14:49
  • @AmartyaGaur I added some details in post edit. I figured out I use autopep8 but where are the settings? – vytaute Oct 24 '21 at 16:59
  • It is fairly common to put the comment on top of the code. I did try a few --ignore tags to make your style work, but it seems not to work as expected. – plasma Jul 31 '23 at 21:36

3 Answers3

3

Comment documenting function behavior should be placed inside function, just below signature. If it is not describing function (is placed outside function) it should have those blank lines. Don't mess with language's conventions, it's very bad idea.

Edit, Further clarification:

"""Module-level comment
"""


def function(): 
    """Function level comment. 
    There are multiple conventions explaining how
    a comment's body should be formed.
    """
    return 0

Christopher
  • 306
  • 1
  • 6
  • Oh, i didnt knew that. So it should be: def MyMethod(): # comment return 0 As I understand? – vytaute Jan 22 '22 at 11:09
  • 1
    Close, but you should be using triple quote strings """content""" as documentation in the function body, because of convention and the fact that they can be retrieved at runtime. – Christopher Feb 09 '22 at 17:19
1

This is due to the code convention (PEP8) of Python. Pylance will correct your code when saving.
This is an excerpt of PEP8 which you can find here:
You should use two spaces after a sentence-ending period.

If the comment describes your function, try using Docstrings.

0

Add --ignore=E302,E265 to python.formatting.autopep8Args can also be an alternative way to ignore the extra two lines between the outer layer comment and code. The downside is that it would not correct the right number of lines between two functions anymore.

similar question here

plasma
  • 287
  • 3
  • 12