Python PEP: blank line after function definition? - python

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.

Related

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

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.

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!

Reformatting Python Multiline Comments and Docstrings in PyCharm [duplicate]

This question already has answers here:
Wrapping comments with line breaks in PyCharm
(5 answers)
Closed 1 year ago.
I use PyCharm Professional 2020.3 with Python 3.8. I want to unwrap automatically and then rewrap multiline comments and docstrings when I change the maximum line length. Is there a tool or add-in I can install to achieve this? If not, is there some other solution?
For example, say I have set my maximum line length to be 88 characters (the Black default). Then a multiline comment and docstring will wrap like this:
"""The summary line of a multi-line docstring should be automatically wrapped. That is to
say that its line break should be moved so that it complies with the required maximum
line length.
:param a_param: int, optional
This is an example parameter, which would exist if this was the docstring for a
function. It should also be automatically wrapped and indented. However, the line
breaks that separate the list of parameters/returned variables must not be removed
when formatted.
"""
# This is an example of a multiline comment that has been wrapped to the given maximum
# line length. Behold how it is both a comment and has been wrapped.
Then, say I set my maximum line width to 120 characters (the PyCharm default). I would then like my multiline comments and docstring to be reformatted like so:
"""The summary line of a multi-line docstring should be automatically wrapped. That is to say that its line break should
be moved so that it complies with the required maximum line length.
:param a_param: int, optional
This is an example parameter, which would exist if this was the docstring for a function. It should also be
automatically wrapped and indented. However, the line breaks that separate the list of parameters/returned variables
must not be removed when formatted.
"""
# This is an example of a multiline comment that has been wrapped to the given maximum line length. Behold how it is
# both a comment and has been wrapped.
Also, I am trying to implement my docstrings with the reStructured Text format. However, I'm still new to documentation in Python, so feel free to critique the above examples.
I believe you are looking for the "textwrap" module, which controls denting, dedenting, paragraph width, etc.

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.

Ending a comment in Python

I have already read this: Why doesn't Python have multiline comments?
So in my IDLE , I wrote a comment:
Hello#World
Anything after the d of world is also a part of the comment.In c++ , I am aware of a way to close the comment like:
/*Mycomment*/
Is there a way to end a comment in Python?
NOTE: I would not prefer not to use the triple quotes.
You've already read there are no multiline comments, only single line. Comments cause Python to ignore everything until the end of the line. You "close" them with a newline!
I don't particularly like it, but some people use multiline strings as comments. Since you're just throwing away the value, you can approximate a comment this way. The only time it's really doing anything is when it's the first line in a function or class block, in which case it is treated as a docstring.
Also, this may be more of a shell scripting convention, but what's so bad about using multiple single line comments?
#####################################################################
# It is perfectly fine and natural to write "multi-line" comments #
# using multiple single line comments. Some people even draw boxes #
# with them! #
#####################################################################
You can't close a comment in python other than by ending the line.
There are number of things you can do to provide a comment in the middle of an expression or statement, if that's really what you want to do.
First, with functions you annotate arguments -- an annotation can be anything:
def func(arg0: "arg0 should be a str or int", arg1: (tuple, list)):
...
If you start an expression with ( the expression continues beyond newlines until a matching ) is encountered. Thus
assert (
str
# some comment
.
# another comment
join
) == str.join
You can emulate comments by using strings. They are not exactly comments, since they execute, but they don't return anything.
print("Hello", end = " ");"Comment";print("World!")
if you start with triple quotes, end with triple quotes

Categories