OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
"""Hello, I am a
multiline comment"""
and
'''Hello, I am a
multiline comment'''
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".
Guido has tweeted about this:
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
Multi-line comments are easily breakable. What if you have the following in a simple calculator program?
operation = ''
print("Pick an operation: +-*/")
# Get user input here
Try to comment that with a multi-line comment:
/*
operation = ''
print("Pick an operation: +-*/")
# Get user input here
*/
Oops, your string contains the end comment delimiter.
Triple-quoted text should NOT be considered multi-line comments; by convention, they are docstrings. They should describe what your code does and how to use it, but not for things like commenting out blocks of code.
According to Guido, multiline comments in Python are just contiguous single-line comments (search for "block comments").
To comment blocks of code, I sometimes use the following pattern:
if False:
# A bunch of code
This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability.
Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it.
Most of script languages don't have multiline comments either. Maybe that's the cause?
See PEP 0008, section Comments
And see if your Python editor offers some keyboard shortcut for block commenting. Emacs supports it, as well as Eclipse, presumably most of decent IDEs does.
From The Zen of Python:
There should be one-- and preferably only one --obvious way to do it.
To comment out a block of code in the Pycharm IDE:
Code | Comment with Line Comment
Windows or Linux: Ctrl + /
Mac OS: Command + /
Personally my comment style in say Java is like
/*
* My multi-line comment in Java
*/
So having single-line only comments isn't such a bad thing if your style is typical to the preceding example because in comparison you'd have
#
# My multi-line comment in Python
#
VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote
'
' This is a VB.NET example
'
Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I'd tend to agree with Ned though.
# This
# is
# a
# multi-line
# comment
Use comment block or search and replace (s/^/#/g) in your editor to achieve this.
I solved this by downloading a macro for my text editor (TextPad) that lets me highlight lines and it then inserts # at the first of each line. A similar macro removes the #'s. Some may ask why multiline is necessary but it comes in handy when you're trying to "turn off" a block of code for debugging purposes.
For anyone else looking for multi-line comments in Python - using the triple quote format can have some problematic consequences, as I've just learned the hard way. Consider this:
this_dict = {
'name': 'Bob',
"""
This is a multiline comment in the middle of a dictionary
"""
'species': 'Cat'
}
The multi-line comment will be tucked into the next string, messing up the
'species' key. Better to just use # for comments.
There should only be one way to do a thing, is contradicted by the usage of multiline strings and single line strings or switch/case and if, different form of loops.
Multiline comments are a pretty common feature and lets face it the multiline string comment is a hack with negative sideffects!
I have seen lots of code doing the multiline comment trick and even editors use it.
But I guess every language has its quirks where the devs insist on never fixing it. I know such quirks from the java side as well, which have been open since the late 90s, never to be fixed!
Because the # convention is a common one, and there really isn't anything you can do with a multiline comment that you can't with a #-sign comment. It's a historical accident, like the ancestry of /* ... */ comments going back to PL/I,
Assume that they were just considered unnecessary. Since it's so easy to just type #a comment, multiline comments can just consist of many single line comments.
For HTML, on the other hand, there's more of a need for multiliners. It's harder to keep typing <!--comments like this-->.
This is just a guess .. but
Because they are strings, they have some semantic value (the compiler doesn't get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the AST, so extracting documentation becomes easier.
Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:
void someFunction()
{
Something
/*Some comments*/
Something else
}
Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:
void someFunction()
{ /*
Something
/* Comments */
Something more*/
}
This is really irritating.
Multiline comments using IDLE on:
Mac OS X, after code selection, comment a block of code with Ctrl+3 and uncomment using Ctrl+4.
Windows, after code selection,
comment a block of code with Ctrl+Alt+3 and uncomment using Ctrl+At+4.
I remember reading about one guy who would put his multi-line comments into a triple-quoted variable:
x = '''
This is my
super-long mega-comment.
Wow there are a lot of lines
going on here!
'''
This does take up a bit of memory, but it gives you multi-line comment functionality, and plus most editors will highlight the syntax for you :)
It's also easy to comment out code by simply wrapping it with
x = '''
and
'''
Related
My CS teacher told me that """ triple quotations are used as comments, yet I learned it as strings with line-breaks and indentations. This got me thinking about - does python completely triple quote lines outside of relevant statements?
"""is this completely ignored like a comment"""
-or, is the computer actually considering this?
Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment.
In python, there is only one type of comment that starts with hash # and can contain only a single line of text.
According to PEP 257, it can however be used as a docstring, which is again not really a comment.
def foo():
"""
Developer friendly text for describing the purpose of function
Some test cases used by different unit testing libraries
"""
<body of the function>
You can just assign them to a variable as you do with single quoted strings:
x = """a multi-line text
enclosed by
triple quotes
"""
Furthermore, if you try in repl, triple quoted strings get printed, had it really been a comment, should it have been printed?:
>>> #comment
>>> """triple quoted"""
'triple quoted'
As someone else already pointed out, they are indeed strings and not comments in Python. I just wanted to add a little more context about your question of "is the computer actually considering it?"
The answer is yes, since it isn't a comment. Take the below code for example:
def my_func():
"""
Some string
"""
print("Hello World!")
my_func()
Trying to run this will actually produce a syntax error because of the indentation.
So as far as I know, triple quotes can be used for both purposes but # is the standard for commenting.
According to this website, what I can understand is that ''' This '''
can be used as a comment and because they are handled as docstrings technically (not tested) ' This ' can also act as a comment depending on where put it. However, even though single and triple quotes can be used as comments, it does not mean that they are comments. For example, # comments are compeletely ignored by the interpreter whereas ''' comments might be loaded into memory (just a probable guess, not confirmed). But from what I can tell, they aren't handled as comments as shown below:
So they are not but they can be used as comments. Generally speaking, use #.
EDIT:
As #BTables pointed out, you will get an indentation error if you don't indent them correctly. So they are indeed handled as strings.
What is the purpose of the colon before a block in Python?
Example:
if n == 0:
print "The end"
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the Python koan “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so any statement that should be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
This question turns out to be a Python FAQ, and I found one of its answers by Guido here:
Why are colons required for the if/while/def/class statements?
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
if a == b
print a
versus
if a == b:
print a
Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
Consider the following list of things to buy from the grocery store, written in Pewprikanese.
pewkah
lalala
chunkykachoo
pewpewpew
skunkybacon
When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?
Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)
pewkah
lalala: (<-- see this colon)
chunkykachoo
pewpewpew
skunkybacon
Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.
Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking "this lines are indented because this lines are like special items.", and it could take a while to realize that that's not the best way to think about indentation.
Three reasons:
To increase readability. The colon helps the code flow into the following indented block.
To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.
To make parsing by python slightly easier.
As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.
It also makes constructs like this possible:
if expression: action()
code_continues()
since having the code for the if immediately following the colon makes it possible for the compiler to understand that the next line should not be indented.
According to Guido Van Rossum, the Python inventor, the idea of using a colon to make the structure more apparent is inspired by earlier experiments with a Python predecessor, ABC language, which also targeted the beginners. Apparently, on their early tests, beginner learners progressed faster with colon than without it. Read the whole story at Guido's post python history blog.
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
And yes, the colon is useful in one-liners and is less annoying than the semicolon. Also style guide for long time recommended break on several lines only when it ends with a binary operator
x = (23 +
24 +
33)
Addition of colon made compound statement look the same way for greater style uniformity.
There is a 'colonless' encoding for CPython as well as colon-less dialect, called cobra. Those did not pick up.
What is the purpose of the colon before a block in Python?
Example:
if n == 0:
print "The end"
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the Python koan “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so any statement that should be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
This question turns out to be a Python FAQ, and I found one of its answers by Guido here:
Why are colons required for the if/while/def/class statements?
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
if a == b
print a
versus
if a == b:
print a
Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
Consider the following list of things to buy from the grocery store, written in Pewprikanese.
pewkah
lalala
chunkykachoo
pewpewpew
skunkybacon
When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?
Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)
pewkah
lalala: (<-- see this colon)
chunkykachoo
pewpewpew
skunkybacon
Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.
Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking "this lines are indented because this lines are like special items.", and it could take a while to realize that that's not the best way to think about indentation.
Three reasons:
To increase readability. The colon helps the code flow into the following indented block.
To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.
To make parsing by python slightly easier.
As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.
It also makes constructs like this possible:
if expression: action()
code_continues()
since having the code for the if immediately following the colon makes it possible for the compiler to understand that the next line should not be indented.
According to Guido Van Rossum, the Python inventor, the idea of using a colon to make the structure more apparent is inspired by earlier experiments with a Python predecessor, ABC language, which also targeted the beginners. Apparently, on their early tests, beginner learners progressed faster with colon than without it. Read the whole story at Guido's post python history blog.
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
And yes, the colon is useful in one-liners and is less annoying than the semicolon. Also style guide for long time recommended break on several lines only when it ends with a binary operator
x = (23 +
24 +
33)
Addition of colon made compound statement look the same way for greater style uniformity.
There is a 'colonless' encoding for CPython as well as colon-less dialect, called cobra. Those did not pick up.
For rapidly changing business rules, I'm storing IronPython fragments in XML files. So far this has been working out well, but I'm starting to get to the point where I need more that just one-line expressions.
The problem is that XML and significant whilespace don't play well together. Before I abandon it for another language, I would like to know if IronPython has an alternative syntax.
IronPython doesn't have an alternate syntax. It's an implementation of Python, and Python uses significant indentation (all languages use significant whitespace, not sure why we talk about whitespace when it's only indentation that's unusual in the Python case).
>>> from __future__ import braces
File "<stdin>", line 1
from __future__ import braces
^
SyntaxError: not a chance
All I want is something that will let my users write code like
Ummm... Don't do this. You don't actually want this. In the long run, this will cause endless little issues because you're trying to force too much content into an attribute.
Do this.
<Rule Name="Markup">
<Formula>(Account.PricingLevel + 1) * .05</Formula>
</Rule>
You should try not to have significant, meaningful stuff in attributes. As a general XML design policy, you should use tags and save attributes for names and ID's and the like. When you look at well-done XSD's and DTD's, you see that attributes are used minimally.
Having the body of the rule in a separate tag (not an attribute) saves much pain. And it allows a tool to provide correct CDATA sections. Use a tool like Altova's XML Spy to assure that your tags have space preserved properly.
I think you can set the xml:space="preserve" attribute or use a <![CDATA[ to avoid other issues, with for example quotes and greater equal signs.
Apart from the already mentioned CDATA sections, there's pindent.py which can, among others, fix broken indentation based on comments a la #end if - to quote the linked file:
When called as "pindent -r" it assumes its input is a Python program with block-closing comments but with its indentation messed up, and outputs a properly indented version.
...
A "block-closing comment" is a comment of the form '# end <keyword>' where is the keyword that opened the block. If the opening keyword is 'def' or 'class', the function or class name may be repeated in the block-closing comment as well. Here is an example of a program fully augmented with block-closing comments:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
It's bundeled with CPython, but if IronPython doesn't have it, just grab it from the repository.
Am I correct in thinking that that Python doesn't have a direct equivalent for Perl's __END__?
print "Perl...\n";
__END__
End of code. I can put anything I want here.
One thought that occurred to me was to use a triple-quoted string. Is there a better way to achieve this in Python?
print "Python..."
"""
End of code. I can put anything I want here.
"""
The __END__ block in perl dates from a time when programmers had to work with data from the outside world and liked to keep examples of it in the program itself.
Hard to imagine I know.
It was useful for example if you had a moving target like a hardware log file with mutating messages due to firmware updates where you wanted to compare old and new versions of the line or keep notes not strictly related to the programs operations ("Code seems slow on day x of month every month") or as mentioned above a reference set of data to run the program against. Telcos are an example of an industry where this was a frequent requirement.
Lastly Python's cult like restrictiveness seems to have a real and tiresome effect on the mindset of its advocates, if your only response to a question is "Why would you want to that when you could do X?" when X is not as useful please keep quiet++.
The triple-quote form you suggested will still create a python string, whereas Perl's parser simply ignores anything after __END__. You can't write:
"""
I can put anything in here...
Anything!
"""
import os
os.system("rm -rf /")
Comments are more suitable in my opinion.
#__END__
#Whatever I write here will be ignored
#Woohoo !
What you're asking for does not exist.
Proof: http://www.mail-archive.com/python-list#python.org/msg156396.html
A simple solution is to escape any " as \" and do a normal multi line string -- see official docs: http://docs.python.org/tutorial/introduction.html#strings
( Also, atexit doesn't work: http://www.mail-archive.com/python-list#python.org/msg156364.html )
Hm, what about sys.exit(0) ? (assuming you do import sys above it, of course)
As to why it would useful, sometimes I sit down to do a substantial rewrite of something and want to mark my "good up to this point" place.
By using sys.exit(0) in a temporary manner, I know nothing below that point will get executed, therefore if there's a problem (e.g., server error) I know it had to be above that point.
I like it slightly better than commenting out the rest of the file, just because there are more chances to make a mistake and uncomment something (stray key press at beginning of line), and also because it seems better to insert 1 line (which will later be removed), than to modify X-many lines which will then have to be un-modified later.
But yeah, this is splitting hairs; commenting works great too... assuming your editor supports easily commenting out a region, of course; if not, sys.exit(0) all the way!
I use __END__ all the time for multiples of the reasons given. I've been doing it for so long now that I put it (usually preceded by an exit('0');), along with BEGIN {} / END{} routines, in by force-of-habit. It is a shame that Python doesn't have an equivalent, but I just comment-out the lines at the bottom: extraneous, but that's about what you get with one way to rule them all languages.
Python does not have a direct equivalent to this.
Why do you want it? It doesn't sound like a really great thing to have when there are more consistent ways like putting the text at the end as comments (that's how we include arbitrary text in Python source files. Triple quoted strings are for making multi-line strings, not for non-code-related text.)
Your editor should be able to make using many lines of comments easy for you.