What makes adding block comments feature in Python so difficult/ unachievable? - python

As you know C language allows multiline comments between the symbols /* and */.
However, there is no such feature in Python. The closest thing is using triple quotes like:
"""
Multiline
Comment-alike
in Python
"""
which is not a true comment. Instead, we just define a string that is not assigned to a variable. I guess this takes some space in the final code unlike single line comments following # symbol.
Python is being updated regularly, and we occasionally end up with very original and innovative usage of syntax. My question is what makes adding block comments so difficult in Python by an update? Why no Python developer gets themselves bothered with it?
EDIT on if multiline comments take space in the final bytecode:
I have modified the same code to see if adding multiline comments affect the size of the final bytecode. py_compile module is used.
pkg.py:
#!/usr/bin/python
print("TEST")
pkg.py (comments added):
#!/usr/bin/python
print("TEST")
"""
Here is a multiline
comment to check
if it affects the
size of the final bytecode.
"""
The result is that the latter code (with the triple quote comment) is 117 bytes while the original one is 115 bytes. Obviously, the comment string is not fully included in the final bytecode. Still, we cannot say multiline comments in Python have no effect on the size of the final code.
Note that single line comments by the symbol # did not increase the size of the final bytecode at all.

Related

Python multiline comments

I am struggling with multi line comments in Python, I understood I can use # at the start of every line of multi line comments but there is also another way of using """ at the start and end of the comment; however, in my interpreter the """ method gives an output instead of ignoring the comment.
>>> """this should
be a multi
line comment"""
And my interpreter gives the following output:
'this should\nbe a multi\nline comment'
Can someone explain it?
Triple quoted strings are used as comments 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 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 it in a repl, triple quoted strings get printed, had it really been a comment, should it have been printed?:
>>> #comment
>>> """triple quoted"""
'triple quoted'
This is very easy to accomplish in python.
# This is a single-line comment
'''
This is a multi-line comment
'''
Just put the comments in ''' and put whatever you want inside of them!

Meaning of an empty line in Python source code file

Will a Python program have exactly the same meaning if I will remove all empty lines from all my source files everywhere, like instead of:
def foo():
x = 1
if True:
bar()
I will do:
def foo():
x = 1
if True:
bar()
Everywhere means EVERYWHERE here. In class definitions, after import statements, etc.
Please do not comment on style and aesthetics. This is a different topic. Same to entering code right into the interpreter. This question is about the source code files.
The similar questions is about adding empty lines. Can I add them in between ANY two lines of code without changing the semantics?
Unfortunately docs are not very explicit here.
If I claim an invalid encoding in the third line after two empty lines, it runs fine:
# -*- coding: foobar -*-
If I remove one or both of the empty lines, this happens:
SyntaxError: encoding problem: foobar with BOM
That's because Python looks for an encoding only in the first two lines. Of course it doesn't have to be an invalid encoding. You also get a difference for a valid encoding other than the default encoding, as the file will be decoded differently then. Again depending on whether it's in the first two lines or not, so empty lines can make a difference there.
See Encoding declarations and also the rest of that page, including Blank lines.
That will be fine. Python is picky about tabbing but doesn't care whether or not you include blank lines in your code.
It won't make a difference in a script except in multi line strings. However, when you are entering code directly into the interpreter, it uses blank lines to detect the end of blocks of code (for loops, function definitions, etc.), so you may get errors.

Python PEP: blank line after function definition?

I can't find any PEP reference to this detail. There has to be a blank line after function definition?
Should I do this:
def hello_function():
return 'hello'
or shoud I do this:
def hello_function():
return 'hello'
The same question applies when docstrings are used:
this:
def hello_function():
"""
Important function
"""
return 'hello'
or this
def hello_function():
"""
Important function
"""
return 'hello'
EDIT
This is what the PEP says on the blank lines, as commented by FoxMaSk, but it does not say anything on this detail.
Blank Lines
Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as
whitespace; Many tools treat these characters as page separators, so
you may use them to separate pages of related sections of your file.
Note, some editors and web-based code viewers may not recognize
control-L as a form feed and will show another glyph in its place.
Read Docstring Conventions.
It says that even if the function is really obvious you have to write a one-line docstring. And it says that:
There's no blank line either before or after the docstring.
So I would code something like
def hello_function():
"""Return 'hello' string."""
return 'hello'
As pointed out by #moliware, the Docstring Conventions state, under One-line Docstrings:
There's no blank line either before or after the docstring.
HOWEVER, it also says (under Multi-line Docstrings):
Insert a blank line after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line.
My interpretation of all this: blank lines should never precede any docstring, and should only follow a docstring when it is for a class.
Projects use different docstring conventions.
For example, the pandas docstring guide explicitly requires you to put triple quotes into a line of their own.
Docstrings must be defined with three double-quotes. No blank lines should be left before or after the docstring. The text starts in the next line after the opening quotes. The closing quotes have their own line (meaning that they are not at the end of the last sentence).
Making a python script simultaneously adhere to pydocstyle and pycodestyle is a challenge. But one thing which greatly helps is that in your docstring write the first line as summary of the function or class within 79 characters including ..This way you adhere to both PEP 257 (as per pydocstyle) of having a period at the end of an unbroken line and 79 characters limit of PEP 8 (as per pycodestyle).
Then after leaving one blank line (for that using new line shortcut of your coditor is better than manually pressing enter) you can write whatever you want and at that time focusing only on pycodestyle which is slightly easier than pydocstyle and the main reason is that our understanding of line and indentation is quite different than what system understands due to indentation settings, tab settings, line settings in the various code editors we use.So in this way you will have TODO from pycodestyle which you understand and can rectify instead of banging your head against the wall on pydocstyle TODOs.

comment out nested triple quotes

In python to comment-out multiple lines we use triple quotes
def x():
"""This code will
add 1 and 1 """
a=1+1
but what if I have to comment out a block of code which already contains lot of other comment out blocks (triple quote comments). For example if I want to comment out this function fully..
"""
def x():
"""This code will
add 1 and 1 """
a=1+1
"""
This doesn't work. How can I comment out such blocks of code.
In python to comment-out multiple lines we use triple commas
That’s just one way of doing it, and you’re technically using a string literal, not a comment. And, although it has become fairly established, this way of writing comments has the drawback you observed: you cannot comment out nested blocks.1
Python doesn’t have nesting multiline comments, it’s as simple as that. If you want to comment out multiple lines allowing for nested comments, the only safe choice is to comment out each line.
Most editors have some command that makes commenting out or in multiple lines easy.
1 For a single level of nesting you can in fact use '''"""nested """''', or the other way round. But I wouldn’t recommend it.
What I often do in brief hack&slay situations is something like this below. It is not really a comment, and it does not cover all cases (because you need to have a block), but maybe it is helpful:
if 0: # disabled because *some convincing reason*
def x():
"""This code will
add 1 and 1 """
a=1+1
Or, if you cannot or don't like to introduce indenting levels between the typical ones:
# disabled because *some convincing reason*
if 0: # def x():
"""This code will
add 1 and 1 """
a=1+1
You should use # for commenting, and at the beginning of each line. This is very easy if you're using eclipse + pydev.
Simply select the block of code to comment, and press Ctrl + \. The same goes for uncommentng as well.
I'm sure there are such easy ways in other editors as well.
I'm taking a Udacity python programming course building a search engine. They use the triple quotes to enclose a webpage's source code as a string in the variable 'page' to be searched for all the links.
page = '''web page source code''' that is searched with a page.find()

## in python using notepad++ syntax coloring

In my editor (notepad++) in Python script edit mode, a line
## is this a special comment or what?
Turns a different color (yellow) than a normal #comment.
What's special about a ##comment vs a #comment?
From the Python point of view, there's no difference. However, Notepad++'s highlighter considers the ## sequence as a STRINGEOL, which is why it colours it this way. See this thread.
I thought the difference had something to do with usage:
#this is a code block header
vs.
##this is a comment
I know Python doesn't care one way or the other, but I thought it was just convention to do it that way.
Also, in a different situations:
Comment whose first line is a double hash:
This is used by doxygen and Fredrik Lundh's PythonDoc. In doxygen,
if there's text on the line with the double hash, it is treated as
a summary string. I dislike this convention because it seems too
likely to result in false positives. E.g., if you comment-out a
region with a comment in it, you get a double-hash.

Categories