How do I create multiline comments in Python?
Asked Answered
M

27

1413

How do I make multi-line comments? Most languages have block comment symbols like:

/*

*/
Mazman answered 8/10, 2011 at 12:51 Comment(8)
I suppose being an interpreted language, it makes sense, as in the case of sh or bash or zsh, that # is the only way to make comments. I'm guessing that it makes it easier to interpret Python scripts this way.Assignee
I know this answer is old, but I came across it because I had the same question. The accepted answer DOES work, though I don't know enough of Python to know the intricacies of why it may not be correct (per ADTC).Magi
@BrandonBarney Let me explain you the issue. The accepted answer, which uses ''', actually creates a multi-line string that does nothing. Technically, that's not a comment. For example, you can write k = '''fake comment, real string'''. Then, print(k) to see what ADTC means.Aerodynamics
That makes so much more sense now. I'm used to vba where creating an unused string results in an error. I didn't realize python just ignores it. It still works for debugging and learning at least, but isn't good practice for actual development.Magi
In Python source code, if you break a long line, the editor automatically indents it, to show that the broken line is really part of the previous line? Is that what I should do if I break up a long line of pseudocode?Pastoralize
In Notepad++ ctrl+k comments the lines selected with #Bilharziasis
@VictorZamanian Python is not "an interpreted language". It has the same compilation model as Java or C#, just with run-time type checks rather than manifest typing.Spiky
@KarlKnechtel From Wikipedia: "Most Python implementations (including CPython) include a read–eval–print loop (REPL), permitting them to function as a command line interpreter for which users enter statements sequentially and receive results immediately."Assignee
M
2155

You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.

'''
This is a multiline
comment.
'''

(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)

Guido van Rossum (creator of Python) tweeted this as a "pro tip".

However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:

# This is a multiline
# comment.

...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.

Myrnamyrobalan answered 8/10, 2011 at 12:58 Comment(28)
Hm. I put a huge multiline string in a python script test.py just to see. When I do import test, a test.pyc file is generated. Unfortunately, the pyc file is huge and contains the entire string as plain text. Am I misunderstanding something, or is this tweet incorrect?Ln
@unutbu, if it was the only thing in the file, it was a docstring. Put some code before it and it'll disappear from the pyc. I edited the answer and put „module“ to the list of things that have docstrings.Myrnamyrobalan
I don't like multiline string as comments. Syntax highlighting marks them as strings, not as comments. I like to use a decent editor that automatically deals with commenting out regions and wrapping multiline comments while I type. Of course, it's a matter of taste.Gerhardine
@Sven, my editor happens to mark them as comments, unless used in an expression. Maybe you could (open a request to) fix the syntax highlighting for your editor? Python does ignore these, so they are comments. But yes, it's a matter of taste.Myrnamyrobalan
While my editor highlights them correctly, I agree that just using ctrl-something to comment/uncomment several lines is simpler and looks better in my opinion (but then I'm also not using /* */ in Java, C# or c++). Just a matter of taste I assume ;)Tantalum
As a convention I find it helpful to use """ for docstrings and ''' for block comments. In this manner you can wrap ''' around your usual docstrings without conflict.Buckwheat
Though not optimally space efficient, I use ''' when I only want a small comment in a line of code.Disenfranchise
While you can use multi-line strings as multi-line comments, I'm surprised that none of these answers refer to the PEP 8 subsection that specifically recommends constructing multi-line comments from consecutive single-line comments, with blank # lines to distinguish paragraphs.Instantly
@AirThomas: Yeah, I agree. Not terribly sure if it's fair to change a 200+ answer from "Use this, it's great and BDFL-blessed" to "You can use this, but it's not something you'd want to commit to the repo", but I went ahead and made the change.Myrnamyrobalan
Additionally whether you use triple-apostrophes, triple-quotation marks or hash/pound comment tokens may depend if you use any third party source code tools that clean up or create document generators that pull text from the source.Lever
I would be cautious about using triple quotes. In Python 2 it seems fine, but I have found libraries that throw errors in Python 3, when \N is in the triple quotes...as it's read like a doc string. Here's an example: ''' (i.e. \Device\NPF_..) ''' That will result in an error as it reads \N and no longer acts like a true comment, but interprets what is in there. Which makes me wonder if compiling is also interpreting the triple quotes... which a real comment shouldn't be considered at compile time, right?Garish
Yes, \N introduces a named Unicode character (try "\N{BLACK STAR}" in Python 3). It does the same thing in Python 2 Unicode strings as well. You'll have the same problem with \x, \u, and \U.Myrnamyrobalan
If your comment includes a long piece of text that you'd like to be able to copy-paste, either you have to put it all on one line or use block comments. Another vote for block comments.Pyrography
fyi, using string-literals (single or tripe-quotes) for comments can lead to strange problems. For example, I recently got an Indentation Error... which I finally figured out was due to there being a triple-quoted '''comment''' right before an elif statement. Since the '''string-literal''' is actually just code that does nothing (not a comment) it does affect indentations.Cormier
@PetrViktorin: The tweet link seems to have changed to twitter.com/gvanrossum/status/112670605505077248. Would you please put the actual text in your answer to protect against link decay?Ln
@HappyLeapSecond: Thanks, I corrected the link. But the tweet is already paraphrased in the answer; copying it wouldn't bring anything new.Myrnamyrobalan
I am allways amazzed about Python's simplicity. Comment are strings in the source code. So comments interpreted by the interpreter as strings, but they are forgotten by the interpreter in the same CPU click as the reference counter of the object is 0. So we needn't any precompiler or soficticated IDE to handle the multiline comments.Esoterica
Using ''' to multi-line comment is terrible procedure as it is not ignored by the interpreter like an actual comment is. It is garbage-collected instantly, but the code is still using resources.Kathie
I have to say this is an extremely poor choice of syntax (the fault of the Python devs, not you). Why? If for not for the many reasons in other comments because most IDE's including Jupyter automatically give you 2 single quotes instead of 1, thus getting 3 is a pain. Yet it would not be worth it to change the behavior. The syntax should just be like the many other more sensible choices out there including /* */.Jaleesa
If you're using an IDE, use its “comment” shortcut – e.g. Ctrl+/ in Jupyter. (And yes, Jupyter automatically adding stuff I didn't actually type drives me up the wall.)Myrnamyrobalan
This answer is incorrect. multiline strings are not the same as a comment. A comment is whitespace and has no semantic interpretation. However, a multiline comment does.Cthrine
@Buckwheat I use your convention, and more: '''block comment''' instead of pass. I find this helpful to explain an empty except-clause or if-else-clause.Ersatz
Btw, the whole multiline string can be toggled "on/off" by putting a single # before the closing '''. Now, if you put another # before the opening ''', the whole section will be code. If you remove the first # again, it will be back to multiline string. Really helpful to temporarily disable several/lots of lines of code easily (unless they contain ''' multiline strings, of course). But then again, you could use double-quotes for your toggle.Compelling
I am getting an indentation error. I did indent the apostrophes correctly. Could you please help me out? is it necessary to indent the apostrophes just like the previous line? Or can I start it from the start of the new physical line?Australorp
Pep8 recommending multi-line strings is yet another big fail on that spec. It's one of the worst things for a language already having major issues. In an age of 3K laptops: 79-character lines (which much of that taken up by the 4-space indentations) anyone??Helen
@javadba PEP 8 does not recommend multi-line strings for comments. Also, PEP 8 explicitly says you can agree on a different line length. (Myself, I like to have several files open side-by-side on the big screen, and also see the whole line on a phone.)Myrnamyrobalan
@PetrViktorin Thx for pointing that out! There are many users of PEP8 that are not aware of that option to use the 99 length.Helen
Yeah, if a string is created without context in a python file, it will be skipped.Dado
L
105

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.


To protect against link decay, here is the content of Guido van Rossum's tweet:

@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)

Ln answered 8/10, 2011 at 12:54 Comment(10)
triple quoted string (''') indeed work to fulfil multi line comments.Jetblack
Thanks.. Used (''') and (""") to comment out the block but it didn't help me for Django applications. So chose IDLE and there are options like Comment out region and Uncomment regions (shortcut: Alt+3 and Alt+4 respectively) under Format menu. Now it is more easier than ever..Keg
You should also consider using a IDE. Yes, they are hefty, but if used properly they can really boost coding time. I personally used to use PyDev, and now use PTVS (with visual studio). I would definitely reccomend PTVS, as it is really nice to work with, containing the above features along with a lot more - direct integration with virtualenvs, and really good debugging, to say the leastDaria
@ADTC: In acknowledgment of Petr Viktorin's answer, I edited my answer to read "Python does have a multiline string/comment syntax".Ln
@HappyLeapSecond I think you should clarify it saying "Python doesn't have a true multiline comment syntax, but supports multiline strings that can be used as comments."Mitinger
What I want is an easy way to comment out whole blocks of code when testing. Other languages make that easy. Python is just a pain.Whalebone
the benefit of multiline comments when developing is helpful when some of the lines in the area are commented and you don't want to confuse them with the good lines of codeBarbarism
I would still consider it bad style, even though Guido says it's ok. Not suitable for releases, but a quick and dirty solution while testing and debugging. Another way to keep around old code while edition a function is to just put return command above it.Xenon
"you would be right to say it is not guaranteed as part of the language specification." - Bytecode is not guaranteed as part of the language specification. The implementation is free to interpret Python code line for line as text, AOT compile it into machine code, or whatever it wants, without necessarily creating bytecode at all. So it's rather strange to pick one very specific implementation detail and call it out in this fashion.Laina
You can always use ' ' ' (triple quotation marks) to create a multi-line string. This is also good because strings get ignored if they are put into code without context (i.e. if they are not assigned to a variable)Dado
R
74

From the accepted answer...

You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You'll get either...

ValueError: invalid \x escape

...on Python 2.x or...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is...

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()
Razorbill answered 29/6, 2016 at 13:4 Comment(4)
Then, you can use r'raw string' -- r'\xor' == '\\xor'.Via
Well, any "true" multi-line comment must also be parsed and syntactically valid. C-style comments can't contain a */ as it will terminate the block, for example.Surbased
@dan1111 that's obvious that comment cannot include end marker, but that's the only limitation.Raouf
''' "comments" have more limitations. You can only comment out whole statements, whereas comments can comment out parts of expression. Example: In C, you can comment out some list elements: int a[] = {1, 2, /* 3, 4, */ 5};. With Multi line string, you can't do that, as that would put a string inside your list.Raouf
W
43

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """
Washcloth answered 16/2, 2015 at 14:0 Comment(3)
triple-quotes are a way to insert text that doesn't do anything (I believe you could do this with regular single-quoted strings too), but they aren't comments - the interpreter does actually execute the line (but the line doesn't do anything). That's why the indentation of a triple-quoted 'comment' is important.Cormier
This solution is incorrect, the weather2 comment is actually a docstring since it's the first thing in the class.Chaperone
Agree with @KenWilliams. This is not a correct solution. Try putting this in the middle of a function/class, and see how it messes up your formatting and automating code folding/linting.Pastoralize
T
30

AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.

If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.

Truthfunction answered 8/10, 2011 at 12:55 Comment(3)
this is incorrect, see the responses on using triple quotes.Laughing
@FernandoGonzalezSanchez: It's really not incorrect. This "multi-line string as comment" can be best described as a "pro-tip". The official Python docs say nothing on this, hence the question posted by OP.Truthfunction
That's a PEP for docstrings; there isn't a single mention of "comment" on that page.Truthfunction
B
19

There is no such feature as a multi-line comment. # is the only way to comment a single line of code. Many of you answered ''' a comment ''' this as their solution.

It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.

Check the official documentation here

Bioenergetics answered 6/10, 2018 at 12:9 Comment(1)
this should be the accepted answerNappie
F
17

I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.

Fatherly answered 8/10, 2011 at 12:54 Comment(0)
P
15

If you put a comment in

"""
long comment here
"""

in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use

# Long comment
# here.

If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.

If you don’t want to use plugins like the above you can use search and replace like

:.,.+1s/^/# /g

This will replace the first character on the current and next line with #.

Pastoralize answered 31/1, 2018 at 18:16 Comment(0)
O
11

Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.

macOS: Select code-block and then +/

Windows: Select code-block and then Ctrl+/

Ossie answered 29/8, 2019 at 4:1 Comment(0)
S
8

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
Slapbang answered 27/6, 2018 at 14:44 Comment(0)
C
8

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string
Contradict answered 29/9, 2019 at 17:38 Comment(0)
F
6

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it's #.

Frith answered 15/9, 2017 at 5:27 Comment(0)
S
5

Multiline comment in Python:

For me, both ''' and """ worked.

Example:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

Example:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
Soupandfish answered 30/8, 2018 at 8:41 Comment(0)
B
5

If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign

print("Hello World")  # printing

If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign

# single line comment

To write comments longer than 1 line, you use 3 quotes

"""
This is a comment
written in
more than just one line
"""
Baba answered 8/9, 2020 at 15:44 Comment(1)
The first two advice seem to be coming from PEP 8. Note that for multiline comments PEP 8 tells us to construct them from consecutive single-line comments, not as multiline strings: python.org/dev/peps/pep-0008/#block-comments.Revis
R
4

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""
Rashid answered 11/5, 2017 at 15:47 Comment(2)
You're saying single quotes create a comment in python 2.7?Volcanology
Using a single set of quotes creates a string. A single line comment should be prefixed with a #.Picky
T
4

The inline comments in Python starts with a hash character.

hello = "Hello!" # This is an inline comment
print(hello)

Hello!

Note that a hash character within a string literal is just a hash character.

dial = "Dial #100 to make an emergency call."
print(dial)

Dial #100 to make an emergency call.

A hash character can also be used for single or multiple lines comments.

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

Hello

World

Enclose the text with triple double quotes to support docstring.

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

Hello John!

Enclose the text with triple single quotes for block comments.

'''
I don't care the parameters and
docstrings here.
'''
Tiffanitiffanie answered 15/12, 2018 at 4:26 Comment(0)
D
3

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")
Dunfermline answered 14/3, 2019 at 7:53 Comment(0)
F
3

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.

Fighterbomber answered 11/6, 2019 at 12:41 Comment(0)
P
2

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 - Comment/uncomment
  • Ctrl + 4 - Comment a block of code
  • Ctrl + 5 - Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================
Pampuch answered 7/11, 2019 at 14:32 Comment(0)
C
2

Yes, you can simply use

'''
Multiline!
(?)
'''

or

"""
Hello
World!
"""

BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:

# This is also
# a multiline comment.

For this one, you can select the text you want to comment and press Ctrl / (or /), in PyCharm and VS Code.

But you can edit them. For example, you can change the shortcut from Ctrl / to Ctrl Shift C.

WARNING!

  1. Be careful, don't overwrite other shortcuts!
  2. Comments have to be correctly indented!

Hope this answer helped. Good luck next time when you'll write other answers!

Ceilidh answered 16/6, 2022 at 11:3 Comment(0)
Y
2

This can be done in Vim text editor.

Go to the beginning of the first line in the comment area.

Press Ctrl+V to enter the visual mode.

Use arrow keys to select all the lines to be commented.

Press Shift+I.

Press # (or Shift+3).

Press Esc.

Yangyangtze answered 21/8, 2022 at 4:7 Comment(0)
S
1

A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.

A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.

Swindell answered 10/12, 2018 at 9:20 Comment(0)
G
1

Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.

For single line you can use Shift + #.

Gmur answered 22/1, 2019 at 11:4 Comment(0)
S
1

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__
Skippet answered 8/7, 2019 at 3:34 Comment(2)
What does this add over the previous answers?Presnell
My answer contains more details, which may help developer more.Skippet
C
1

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__
Carbylamine answered 21/1, 2020 at 18:9 Comment(2)
"DockString"? Do you have a reference?Presnell
@PeterMortensen here you go datacamp.com/community/tutorials/docstrings-pythonCarbylamine
T
1

in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments. in mac: it should be comment + /

Tablespoon answered 13/8, 2022 at 13:32 Comment(0)
P
0

I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:

block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
    def __init__(self):
        # create the event object inside raising class
        self.on_thing_happening = Event()

    def doing_something(self):
        # raise the event inside the raising class
        self.on_thing_happening()        
        
        
class ExampleEventHandlingClass():
    def __init__(self):
        self.event_generating_thing = ExampleEventSource()
        # add event handler in consuming class
        event_generating_thing.on_thing_happening += my_event_handler
        
    def my_event_handler(self):
        print('handle the event')
]#'''


class Event():
 
    def __init__(self):
        self.__eventhandlers = []
 
    def __iadd__(self, handler):
        self.__eventhandlers.append(handler)
        return self
 
    def __isub__(self, handler):
        self.__eventhandlers.remove(handler)
        return self
 
    def __call__(self, *args, **keywargs):
        for eventhandler in self.__eventhandlers:
            eventhandler(*args, **keywargs)

Pros

  1. It is obvious to any other programmer this is a comment. It's self-descriptive.
  2. It compiles
  3. It doesn't show up as a doc comment in help()
  4. It can be at the top of the module if desired
  5. It can be automated with a macro.
  6. [The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
  7. If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.

Cons

  1. It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
  2. It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
  3. It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
  4. It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.

Here's an attempt at the VS Code macro, although I haven't tested it yet:

{
    "key": "ctrl+shift+/",
    "command": "editor.action.insertSnippet",
    "when": "editorHasSelection"
    "args": {
        "snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
    }
}
Philistine answered 23/9, 2022 at 15:57 Comment(2)
what is the official way that pylint wont complain about? pylint complains about the use of ''' with "pylint: String statement has no effect"Tuckerbag
@user1689987, there is no official way provided. That's the problem. You could assign that whole "comment", which is just a string, to a dummy variable and that warning will go away. I would name the variable commentPhilistine

© 2022 - 2024 — McMap. All rights reserved.