The comment block for Python

Hello, It’s a pleasure to be able to share this with you all. I know you’re a great community, and I hope you like this idea.

"Not everything that is efficient is beautiful."

Yes, you heard right, Yes, you heard right, I’ve seen other attempts to make comments in Python allow blocks

  1. “Just comment line by line. Just comment line by line”: It’s been repeated many times, it almost seems like dogma, IDEs automated it, but I believe we are more than that
  2. “#| |#”, “#! #!”, “@@@ @@@” /* */: These are some ideas from the community to address this, but in my opinion (I don’t know if you share it) they are anti-Python, think about it, adds unnecessary syntactic overhead, and the solutions are quite generic; we need something more in the style of Python.
  3. My approach: use a combination of existing symbols, nothing complex, combine the # + """ = #""",It’s simple: combine the triple double quote code, which is already used to create string blocks (and is misused to comment code blocks), and you won’t have the string problem (which it does have to use only triple double quotes)

Examples

#To be able to version your code To be able to version your code

# This is a line comment

print("example funcionality")

#Instead, this would be the hypothetical block comment (multi-line)

#"""

print("deactivate functionality")

#""" 


Does this remind you of anything? Yeah, it’s identical to multi-line strings, which makes implementation trivial (well, almost)

Pseudo-code of python lexer

if actual_character == "#":

    if three_next_characters == '"""':

        # Modo bloque: saltar hasta encontrar #""" (que es # + 3 comillas)

        while current_position < len(code):

            if current_character == '#':

                if three_next_characters == '"""':

                    break  # Cierre encontrado

            advance()

    else:

        # Modo línea: saltar hasta newline

        while current_character != '\n':

            advance()


PD: Thank you, Jelle Zijlstra, Thank you for encouraging me to publish my idea in the community, and for taking the time to read my pull request.

I want to add something I didn’t mention in my initial post that is key: the emergent effect of ##“”".

Look at this:

python

#"""

print("Dead")

#"""



##"""

print("LIVE, the block is cancelled")

##"""


Simply adding a # at the beginning of the delimiter turns the block into a normal inline comment. You don’t need a special rule in the lexer. It’s a natural consequence of # always starting

Simply adding a # at the beginning of the delimiter turns the block into a normal inline comment. You don’t need a special rule in the lexer. It’s a natural consequence of # always starting

This allows:

Native versioning — you can have multiple versions of code and activate/deactivate them with a single character

Nesting — you can add layers of # to comment blocks within blocks.

Nesting — you can add layers of # to comment blocks within blocks.

Isn’t it great? :grinning_face_with_smiling_eyes:

That’s a breaking change. The following code is currently valid, but would be broken under your proposal:

#"""
print("Hallo")
#"""

Long story short, “use a combination of existing symbols” is not a particularly good design principle. While I do not propose to add any new way to write comments to Python, the addition of C-style comments /* ... */ (which has been proposed before) would actually not be a breaking change since the current Python grammar does not allow cases where a / token is followed by a * token.

4 Likes

Most modern IDEs / Editors (like VSCode) support this already. You can have a key bind (for me ctrl + #) to comment/uncomment a block in any language while keeping new lines and indentation intact.

Also, your second point about nesting is repeated…

Edit: Fixed parenthesis..

2 Likes

I appreciate your criticism, and it’s true, plus it’s simple to implement.

(But the IDE solution doesn’t have free pop-up versioning that lets you refactor code with a “sed” command. Furthermore, the idea of /* would add operand overload on top of / (which is already division and integer division))

Thanks for the criticism, but honestly, it sounds like IDE elitism (I know that’s not what you meant, but think about how much RAM most IDEs that use that use—quite a lot). My proposal is simple.And I’ve even implemented it in C and assembler, since it copies the triple quote system (which already works for text) but for comments (the same search code without inventing anything new, and Furthermore, it is practically very unlikely that there are codes that use #“”", (i.e., it is backward compatible)

1 Like

I’m not really sure what you mean here. Do you mean that it would literally require an operator overload for division? If so, that’s not the case; the RHS wouldn’t even be a valid Python expression. Do you mean that it’s just another use case for the / symbol that people would have to keep in their heads? If so, that wouldn’t really be a problem; the contexts are just so obviously different that it shouldn’t matter.

I’m not particularly for or against the /* ... */ multiline syntax in Python, but I don’t think this argument against it is a particularly good one.

See this code search, which has over 97 thousand hits. “It’s unlikely” is not a good reason to release a breaking change unless you have very, very solid proof of that.

1 Like

Andrew, you’re right that there are 97,000 views on GitHub. But the vast majority of those are uses of #“”" as a hack for block comments. My proposal doesn’t break those uses; it legitimizes them. And in the unlikely event that someone has used #“”" as a normal inline comment, the change doesn’t affect their code because inline comments are ignored anyway. So there’s no real change.

1 Like

This is currently valid code that prints Hallo. Your change would stop it from printing Hallo.

2 Likes

“Unlikely” does not mean “impossible”, and actually, I’ve quite often used the commenting-out of a triple quoted string’s opening as a means of quickly enabling/disabling a block of code. Granted, I usually write # """ with a space in it, but it’s entirely possible that I’d miss out the space occasionally, since it’s normally not a problem to do so.

So this will have the potential to cause breakage. The question is, is it worth that? Is the ability to make block comments worth potentially changing the meaning of existing code, without any error message? It’s a very subtle form of breakage; most programs will continue to work correctly, but the ones that break will do so in a very strange way.

Personally, I don’t think so. Block comments are a nice-to-have, but not immensely valuable (Python’s managed a few decades without them, after all).

You seem to have something against IDEs. I don’t blame you for disliking the heavyweight “all-inclusive” IDEs, but there are plenty of text editors that don’t use a huge amount of RAM, and yet have a way to block comment/uncomment code in various languages. For example, the editor I use is SciTE, and I can select a block of text and hit Ctrl-Q to toggle comment; and this works in basically any language. I’m not sure what you’ll consider a fair test of measure memory usage, but I keep SciTE running permanently on my laptop with 4GB of memory; he struggles to load web pages with too much JS in them some days, but SciTE is still lean. According to top it’s using about 20MB of RSS, putting it roughly comparable to (and a little below) Thunar the file manager.

All this is not to say that this is a useless proposal, but just that the juice isn’t worth the squeeze.

This one would break with this change since most of the function would disappear.

This one would break since the print calls would disappear.

This one would probably be a syntax error since the opening #""" is never terminated.

This one would also syntax error since the multiline comment would hide the function headers, causing an indentation error.

“The vast majority” of cases is not an okay threshold; if you’re breaking anyone’s compliant code, you need a very compelling reason to do so. In this case, block comments are arguably not necessary in the first place (“many single-line comments work fine”), and if they are necessary, there are alternative, non-breaking syntaxes that would do the job.

Except that it DOES break them. I did probably the same GitHub search you did and started looking through the first hits:

This opens with """# and closes with ##""" so it’s a perfectly normal triple quoted string, and wouldn’t be affected by this proposal. (It’s not being legitimized, it’s completely untouched.)

This would suddenly disable code that is meant to be active. I’m not sure what the author’s intent is here, but this block of code would change meaning under your proposal.

So would these. Presumably the intention in these examples is to be able to easily disable the code; you could call that a code smell, but it’s still going to result in a behavioural change, removing blocks of code that existing versions of Python execute.

You’re right, Eneg. It’s a case where the code changes its behavior. But consider this: does anyone intentionally write #“”" to make the code run? It’s an edge case that can be solved with a space. Besides, most uses of #“”" on GitHub are precisely for what I’m suggesting: commenting out blocks.

Chris, I understand your concern. And you’re right that the extra benefit might not be worth the effort. But consider this: my proposal isn’t just about block comments. It’s about a layering system that enables native versioning. That’s something no IDE can do. And it’s something Python doesn’t have. Isn’t it worth at least considering?

I don’t understand. What is “native versioning” if it isn’t just commenting out one block of code and uncommenting another? (Also, in general, versioning should be done by your source control system, not comments in the code. But that’s a separate point.) Since IDEs can already do block (un)commenting, what’s different about native versioning?

WTF, Yes, it’s true, the codes break, so I write a bash script to fix those conflicts with just a few lines.

It’s lucky that Python isn’t compiled, because we all have the ability to read and edit code, right? Thanks for your feedback.

1 Like

Native versioning is quite simple, you’re going to love it, here’s an example .

#“”"

code deactivate

#“”"

##“”"

code activated # because # Cancels the #“”" rule

##“”",

###“”"

code also activated

###“”"

you just need erase one # for switch between anidated versions,this emerge for the #“”"

This alone infine anidated without use ram and stack

Chris, entiendo tu confusión. Los IDEs pueden comentar/descomentar bloques, pero no pueden hacer esto:

python

#“”" VERSIÓN 1 (estable)

def procesar(data):

return data \* 2

#“”"

##“”" VERSIÓN 2 (experimental)

def procesar(data):

return \[x \* 2 for x in data\]

##“”"

Con un solo sed, puedo cambiar la versión activa:

bash

sed -i ‘s/^#“”“/##”“”/g’ archivo.py

sed -i ‘s/^##“”“/#”“”/g’ archivo.py

Eso es nativo. No depende de un IDE. Y permite anidamiento infinito sin usar memoria ni stack.

¿Puede un IDE hacer eso?

(Ups, I said it in Spanish, it doesn’t matter, they have a translator, right?

Chris, I understand your confusion. IDEs can comment/uncomment blocks, but they can’t do this:

python

#“”" VERSION 1 (stable)

def process(data):

return data \* 2

#“”"

##“”" VERSION 2 (experimental)

def process(data):

return \[x \* 2 for x in data\]

##“”"

With a single sed, I can switch the active version:

bash

sed -i ‘s/^#“”“/##”“”/g’ file.py

sed -i ‘s/^##“”“/#”“”/g’ file.py

That’s native. It doesn’t depend on an IDE. And it allows infinite nesting without using memory or stack.

Can an IDE do that?

(Okay, I’ve translated it, I hope it’s helpful. )

Slow mode has been enabled to give participants time to consider their points before responding. Please review our Participation Guidelines. Remember, you do not have to continue participating in a topic if you’ve made your point, trust the SC to take in the full context if it comes to them making a decision. Remember, you do not need to respond immediately to every reply.

2 Likes