98

Is there a method of ending single line comments in Python?

Something like

/* This is my comment */ some more code here...
0

9 Answers 9

107

No, there are no inline comments in Python.

From the documentation:

A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax; they are not tokens.

Sign up to request clarification or add additional context in comments.

Comments

51

Whitespace in Python is too important to allow any other kind of comment besides the # comment that goes to the end of the line. Take this code:

x = 1
for i in range(10):
             x = x + 1
/* Print. */ print x

Because indentation determines scope, the parser has no good way of knowing the control flow. It can't reasonably eliminate the comment and then execute the code after it. (It also makes the code less readable for humans.) So no inline comments.

5 Comments

I'm not sure there is any need to blame this on the parser's sensitivity to whitespace. You could just say that the line starts where the comment starts if you wanted... I think it's more the philosophy that the middle of a line is no place for a comment. :-)
The parser isn't the only thing that reads the code... Personally, I would rather read python where lines start where the characters start. It's not a huge deal, but it's the little things that make python easy and fun.
@ABMagil that is true... a human parser is probably more error-prone than the actual parser :)
I agree that comments inline before or after code are "ugly". But it can be very useful to comment out a specific part (inline) while debugging and I'd like to do the following (new lines after each '\'): data_frame \ # .coalesce(1) \ .write \ .option('header', 'true') \ # Comment about csv file format \ .csv(file_name)
But what about line continuations? The sequence, \#, raises a SyntaxError because apparently they decided to make whitespace a part of the line continuation token. I can't even move it to the next line because the comment terminates the line continuation. Why? This behavior is nonsensical. The sequence \^J# should just result in an implicit line continuation continuation after the comment terminates, or \# should be allowed, or there needs to be a dumb inline comment that interprets [comment] stuff as just ` stuff`, all consequences included.
16

You can insert inline comment. Like this

x=1; """ Comment """; x+=1; print(x);

And my python version is "3.6.9"

1 Comment

Not very "pythonic" but it does what is asked. Works in any Python version.
7

I miss inline-comments mainly to temporarily comment out parameters in functions or elements in list/dicts. Like it is possible in other languages:

afunc(x, /*log=True*/, whatever=True)
alist = [1,2,3]

The only workaround, i guess, is to but them on separate lines like:

afunc(
    x,
    # log=True,
    whatever=True,
)

alist = [
   1,
   # 2,
   3,
]

However, as python is often used as rapid prototyping language and functions (due to no overloading) often have lots of optional parameters, this solution does not fell very "pythonic"...

Update

I meanwhile really like the "workaround" and changed my opinion about being not pythonic. Also, some formatters like Black will automatically arrange arguments or elements of an array/dict on seperate lines if you add a comment at the end. This is called Magic Trailing Comma

Comments

4

This is pretty hideous, but you can take any text convert it into a string and then take then length of that string then multiply by zero, or turn it into any kind of invalid code. example

history = model.fit_generator(train_generator,steps_per_epoch=8,epochs=15+0*len(", validation_data=validation_generator"), validation_steps=8,verbose=2)

3 Comments

How this relates to the question in any way?
@Hamza The string part can be considered as an inline comment.
This is genius! ... Evil genius, but still ... genius is genius :-)
4

No, there are no inline-block comments in Python. But you can place your comment (inline) on the right. That's allows you to use syntax and comments on the same line. Anyway, making comments to the left of your code turn reading difficult, so...

Ex:

x = 1 # My variable

Comments

1

If you're doing something like a sed operation on code and really need to insert plain text without interfering with the rest of the line, you can try something like:

("This is my comment", some more code here...)[1]

Eg.,

my_variable = obsolete_thing + 100

could be transformed with sed -e 's/obsolete_thing/("replacement for &", 1345)[1]/' giving:

my_variable = ("replacement for obsolete_thing", 1234)[1] + 100

Comments

1

The octaves of a Piano are numbered and note frequencies known (see wikipedia). I wanted to inline comment the notes in a list of frequencies while maintaining standard Human readable sequencing of notes. Here is how I did it; showing a couple of octaves.

def A(octave, frequency):
    "Octave numbering for twelve-tone equal temperament"
    return frequency

NOTE=[
    155.5635 , 164.8138, 174.6141, 184.9972, 195.9977, 207.6523,
A(3,220.0000), 233.0819, 246.9417, 261.6256, 277.1826, 293.6648,
    311.1270 , 329.6276, 349.2282, 369.9944, 391.9954, 415.3047,
A(4,440.0000), 466.1638, 493.8833, 523.2511, 554.3653, 587.3295]

Of course, adjust setup.cfg and comment to satisfy pycodestyle, pyflakes, and pylint.

I argue that maintaining columns and annotating A4 as A(4,440) is superior to enforcing rigid style rules.

A function ignoring a formal argument is run once at list initialization. This is not a significant cost. Inline commenting is possible in python. You just have to be willing to bend style rules.

Comments

-1

There are two options can be used to comment

  1. Single line comments # your comments here #. Indentation doesn't matter. However it depends on the IDE one uses. Some IDE's consider indentation as well. 2)Multiple lines comments """ your code here with multiple lines """. Indentation doesn't matter.

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Thanks, but I can't see how it differs from the existing answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.