Starting to program in Python, I see some scripts with comments using # and """ comments """.
What is the difference between these two ways to comment?
The best thing would be to read PEP 8 -- Style Guide for Python Code, but since it is longish, here
is a three-liner:
Comments start with # and are not part of the code.
String (delimited by """ """) is actually called a docstring and is used on special places for defined purposes (briefly: the first thing in a module or function describing the module or function) and is actually accessible in the code (so it is a part of the program; it is not a comment).
Triple quotes is a way to create a multi-line string and or comment:
"""
Descriptive text here
"""
Without assigning to a variable is a none operation that some versions of Python will completely ignore.
PEP 8 suggests when to use block comment/strings, and I personally follow a format like this:
Example Google Style Python Docstrings
The string at the start of a module, class or function is a docstring:
PEP 257 -- Docstring Conventions
that can be accessed with some_obj.__doc__ and is used in help(...). Whether you use "Returns 42" or """Returns 42""" is a matter of style, and using the latter one is more common, even for single-line documentation.
A # comment is just that, a comment. It cannot be accessed at runtime.
The # means the whole line is used for a comment while whatever is in between the two """ quotes is used as comments so you can write comments on multiple lines.
As the user in a previous answer stated, the triple quotes are used to comment multiple lines of code while the # only comments one line.
Look out though, because you can use the triple quotes for docstrings and such.
Related
i want to know how documentation a python function when one of parameters is a object of package for example a pandas DataFrame.
i use this method but PyCharm(python IDE) doesn't understand it.
def foo(df , no , l_int):
'''
Parameters
-------------
df:Pandas DataFrame
no:int
l_int:list of int
Returns
-------------
'''
in PyCharm it show this:
def foo(df: Any,
no: int,
l_int: list[int]) -> None
Is it a Standard way to solve this issue.
thank you.
Let me tell you a general rule of thumb. If your parameters are encapsulated data as you have in the case of DataFrame then give an example by showing the internal structure of the datatype of the parameter or return datatype e.g.
"""
Parameters
-------------
df:Pandas DataFrame : (here some explanation)
no:int
l_int:list of int
Examples:
df:
{
Give a detailed example by showing the internal data of the datatype so that anyone reading the docstring knows exactly what is encapsulated by this datatype
}
-------------
"""
Code layout
Always use four spaces to indent code. Do not use tabs, tabs
introduce confusion and are best left out.
Wrap your code so that lines don’t exceed 79 characters. This helps users with small displays and makes it possible to have several code files open side by side on larger displays.
When vertical aligning text, there should be no arguments on the first line
Whitespace
Use 2 blank lines around top-level functions and classes.
Use 1 blank line to separate large blocks of code inside functions.
1 blank line before class method definitions.
Avoid extraneous whitespace.
Use blank lines sparingly.
Always surround binary operators with a space on either side but group them sensibly.
Don’t use spaces in keyword arguments or default parameter values.
Don’t use whitespace to line up operators.
Multiple statements on the same line are discouraged.
Avoid trailing whitespace anywhere
Comments
Comments should be complete sentences in most cases.
Keep comments up to date
Write in “Strunk & White “English
Inline comments should be separated by at least two spaces from
the statement and must start with ‘#’ and a single space.
Block comments should be indented to the same level as the code
that follows them.
Each line in block comments starts with ‘#’.
Write docstrings for all public modules, functions, classes and
methods.
Docstrings start and end with """ e.g """ A Docstring. """.
Single line docstrings can all be on the same line.
Docstrings should describe the method or function’s effect as a
command.
Docstrings should end in a period.
When documenting a class, insert a blank line after the docstring.
The last """ should be on a line by itself
For further detail on this topic. Please read PEP 257 or it summary by here
This is the standard way since Python 3.5 though it has evolved quite a bit since it was introduced.
One thing I would do is change the type of df to pandas.DataFrame to make it more expressive.
Also, it looks like PyCharm understood your method just fine. The reformatting was simply to add the type declarations.
Any is not a descriptive type annotation. You want a Pandas dataframe specifically, or pd.DataFrame, but PyCharm doesn't seem to be able to infer that.
The function header should read:
import pandas as pd
def foo(df: pd.DataFrame,
no: int,
l_int: list[int]) -> None
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.
This question already has answers here:
Python comments: # vs. strings
(3 answers)
Closed 9 years ago.
I know two ways of leaving comments in python. One is using """ and the other is using #. I know that the first can be used to return a functions help as a benefit. But when should I use one and when the other? And also how do I have to leave comments? Do I have to press tab and arrange the first line of comment with the the command beneath it? Or do I have to start from the beginning of the line?
No, there is only one way of commenting, using #:
A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.
Triple quoting, """, creates a string object, which happens to be used as the docstring when it is the first line of a function, module or a a class. Triple quoting is useful in many other places too, but should not be confused with commenting. You can use a triple quoted string like any other string literal, with the specific benefit that you can use actual newlines in your source code instead of having to use \n escape characters.
Although it can be used to disable a block of code by turning it into a multi-line string instead, you really should not do this. Use proper source code control and simply delete the block, or use an editor that lets you comment out whole blocks by inserting # for you instead.
For actual comments, use #. The Python style guide (PEP 8) has some things to say about when and how to use commenting; it has this to say about indentation:
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Why didn't python just use the traditional style of comments like C/C++/Java uses:
/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
Is there a specific reason for this or is it just arbitrary?
Python doesn't use triple quotation marks for comments. Comments use the hash (a.k.a. pound) character:
# this is a comment
The triple quote thing is a doc string, and, unlike a comment, is actually available as a real string to the program:
>>> def bla():
... """Print the answer"""
... print 42
...
>>> bla.__doc__
'Print the answer'
>>> help(bla)
Help on function bla in module __main__:
bla()
Print the answer
It's not strictly required to use triple quotes, as long as it's a string. Using """ is just a convention (and has the advantage of being multiline).
A number of the answers got many of the points, but don't give the complete view of how things work. To summarize...
# comment is how Python does actual comments (similar to bash, and some other languages). Python only has "to the end of the line" comments, it has no explicit multi-line comment wrapper (as opposed to javascript's /* .. */). Most Python IDEs let you select-and-comment a block at a time, this is how many people handle that situation.
Then there are normal single-line python strings: They can use ' or " quotation marks (eg 'foo' "bar"). The main limitation with these is that they don't wrap across multiple lines. That's what multiline-strings are for: These are strings surrounded by triple single or double quotes (''' or """) and are terminated only when a matching unescaped terminator is found. They can go on for as many lines as needed, and include all intervening whitespace.
Either of these two string types define a completely normal string object. They can be assigned a variable name, have operators applied to them, etc. Once parsed, there are no differences between any of the formats. However, there are two special cases based on where the string is and how it's used...
First, if a string just written down, with no additional operations applied, and not assigned to a variable, what happens to it? When the code executes, the bare string is basically discarded. So people have found it convenient to comment out large bits of python code using multi-line strings (providing you escape any internal multi-line strings). This isn't that common, or semantically correct, but it is allowed.
The second use is that any such bare strings which follow immediately after a def Foo(), class Foo(), or the start of a module, are treated as string containing documentation for that object, and stored in the __doc__ attribute of the object. This is the most common case where strings can seem like they are a "comment". The difference is that they are performing an active role as part of the parsed code, being stored in __doc__... and unlike a comment, they can be read at runtime.
Triple-quotes aren't comments. They're string literals that span multiple lines and include those line breaks in the resulting string. This allows you to use
somestr = """This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is\
significant."""
instead of
somestr = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
Most scripting languages use # as a comment marker so to skip automatically the shebang (#!) which specifies to the program loader the interpreter to run (like in #!/bin/bash). Alternatively, the interpreter could be instructed to automatically skip the first line, but it's way more convenient just to define # as comment marker and that's it, so it's skipped as a consequence.
Guido - the creator of Python, actually weighs in on the topic here:
https://twitter.com/gvanrossum/status/112670605505077248?lang=en
In summary - for multiline comments, just use triple quotes. For academic purposes - yes it technically is a string, but it gets ignored because it is never used or assigned to a variable.
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
'''