Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to comment functions in Python?

Tags:

python

Is there a generally accepted way to comment functions in Python? Is the following acceptable?

#########################################################
# Create a new user
#########################################################
def add(self):
like image 734
ensnare Avatar asked Oct 12 '22 07:10

ensnare


People also ask

How do you comment in Python correctly?

Comments in Python begin with a hash mark ( # ) and whitespace character and continue to the end of the line. Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command.

How do you properly comment a function?

The single line comment is //. Everything from the // to the end of the line is a comment. To mark an entire region as a comment, use /* to start the comment and */ to end the comment.


2 Answers

The correct way to do it is to provide a docstring. That way, help(add) will also spit out your comment.

def add(self):
    """Create a new user.
    Line 2 of comment...
    And so on... 
    """

That's three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn't need to be multiline and double quotes can be replaced by single quotes.

See: PEP 257

like image 406
Chinmay Kanchi Avatar answered Oct 16 '22 19:10

Chinmay Kanchi


Use docstrings.

This is the built-in suggested convention in PyCharm for describing function using docstring comments:

def test_function(p1, p2, p3):
    """
    test_function does blah blah blah.

    :param p1: describe about parameter p1
    :param p2: describe about parameter p2
    :param p3: describe about parameter p3
    :return: describe what it returns
    """ 
    pass
like image 77
Shwetabh Shekhar Avatar answered Oct 16 '22 21:10

Shwetabh Shekhar