What is the proper way to comment functions in Python?

Question:

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

#########################################################
# Create a new user
#########################################################
def add(self):
Asked By: ensnare

||

Answers:

Read about using docstrings in your Python code.

As per the Python docstring conventions:

The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.

Answered By: Mat Nadrofsky

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

Answered By: Chinmay Kanchi

I would go for a documentation practice that integrates with a documentation tool such as Sphinx.

The first step is to use a docstring:

def add(self):
 """ Method which adds stuff
 """
Answered By: jldupont

Use a docstring:

A string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__ ), but two types of extra docstrings may be extracted by software tools:

  1. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called “attribute docstrings”.
  2. String literals occurring immediately after another docstring are called “additional docstrings”.

Please see PEP 258 , “Docutils Design Specification” [2] , for a detailed description of attribute and additional docstrings…

Answered By: Deniz Dogan

Use a docstring, as others have already written.

You can even go one step further and add a doctest to your docstring, making automated testing of your functions a snap.

Answered By: Tim Pietzcker

The principles of good commenting are fairly subjective, but here are some guidelines:

  • Function comments should describe the intent of a function, not the implementation
  • Outline any assumptions that your function makes with regards to system state. If it uses any global variables (tsk, tsk), list those.
  • Watch out for excessive ASCII art. Having long strings of hashes may seem to make the comments easier to read, but they can be annoying to deal with when comments change
  • Take advantage of language features that provide ‘auto documentation’, i.e., docstrings in Python, POD in Perl, and Javadoc in Java
Answered By: Dancrumb

I would go a step further than just saying “use a docstring”. Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.

Answered By: PaulMcG

While I agree that this should not be a comment, but a docstring as most (all?) answers suggest, I want to add numpydoc (a docstring style guide).

If you do it like this, you can (1) automatically generate documentation and (2) people recognize this and have an easier time to read your code.

Answered By: Martin Thoma

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
Answered By: Shwetabh Shekhar

You can use three quotes to do it.

You can use single quotes:

def myfunction(para1,para2):
  '''
  The stuff inside the function
  '''

Or double quotes:

def myfunction(para1,para2):
  """
  The stuff inside the function
  """
Answered By: user13096898

The correct way is as follows:

def search_phone_state(phone_number_start,state,dataframe_path,separator):  
   """
   returns records whose phone numbers begin with a phone_number_start and are from state
   """
   dataframe = pd.read_csv(filepath_or_buffer=dataframe_path, sep=separator, header=0)
   return dataframe[(pd.Series(dataframe["Phone"].values.tolist()).str.startswith(phone_number_start, na="False"))& (dataframe["State"]==state)]

If you do:

help(search_phone_state)

It will print:

Help on function search_phone_state in module __main__:

search_phone_state(phone_number_start, state, dataframe_path, separator)
returns records whose phone numbers begin with a phone_number_start and are from state
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.