285

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

#########################################################
# Create a new user
#########################################################
def add(self):
1
  • In summary - use a docstring immediately AFTER the function definition.
    – dataman
    Nov 11, 2023 at 14:33

12 Answers 12

455

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

10
  • 18
    Note that it doesn't have to be triple-quoted; any string literal will work. But you can put more information in a multiline string. Mar 1, 2010 at 16:25
  • 9
    Though convention dictates that it should be triple-quoted. I've never seen a docstring that wasn't. Mar 1, 2010 at 16:27
  • 3
    Which is not to say that I don't agree. They should be triple quoted, but you will see some in the wild that aren't.
    – jcdyer
    Mar 1, 2010 at 18:22
  • 9
    You can also use three single-quotes (rather than three double-quotes) to open and close the docstring. Mar 1, 2010 at 23:39
  • 2
    @ChinmayKanchi According to PEP 8 the last triple-quote should be on its own line. Oct 26, 2014 at 2:23
117

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
7
  • Shouldn't that be indented (after the line with def)? (Not a rhetorical question.) Feb 3, 2020 at 16:53
  • 1
    I like this style but when I hover over my function all I get is args -> <return type> it does not show any of the descriptive information, any ideas? Jan 15, 2021 at 23:47
  • 1
    @RicardoSanchez In which IDE do you get this style? VS code usually displays everything after hovering and Pycharm does not display anything if you hover. Mar 25, 2021 at 7:15
  • 1
    @ShwetabhShekhar I just checked again and it does works on VSCode, it must has been after an update, thank you. Mar 25, 2021 at 9:12
  • 1
    IntelliJ IDEA gives a "Loose punctuation mark." warning Mar 21, 2022 at 14:57
30

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.

1
  • 10
    This answer is quite weak without following through to the linked page.
    – xaxxon
    Apr 10, 2019 at 21:49
22

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...

0
12

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
2
  • 8
    there is nothing subjective about this, Python is very clear about using Docstring commenting.
    – user177800
    Mar 1, 2010 at 16:37
  • @fuzzy lollipop, I appreciate the comment, but you'll note that my last point makes that exact point. Perhaps the OP's question is only about the mechanics of commenting in Python, but I don't think my answer warrants down-voting
    – Dancrumb
    Mar 1, 2010 at 16:56
8

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
 """
7

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.

2

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.

1

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.

0
1

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
  """
1

You can go one step further and document the rest of your method.

This may be a bit much at times, but in certain situations, it will help the use and understanding of your code(for example, if you are developing a public API, etc).

Like this;

def get_most_recent_filename(dir:str, prefix:str, extension:str) -> str:
    """
    Get the most recent filename in a directory matching a specified prefix and extension.

    Parameters
    ----------
    dir : str
        The directory in which to search for files.
    prefix : str
        The desired prefix of the file name.
    extension : str
        The desired file extension (e.g., '.txt').

    Returns
    -------
    str
        The full path to the most recent file matching the criteria, 
    or None if no matching files are found.

    Description
    -----------
    This function searches the specified directory for files with a 
    given prefix and extension. 
    It returns the full path to the most recent file that matches 
    the criteria, allowing you to easily access or process the most 
    recent file in a directory.

    If no matching files are found or if the directory does not exist, 
    the function returns None.

    Examples
    --------
    >>> get_most_recent_filename("/path/to/directory", "data_", ".csv")
    '/path/to/directory/data_20231030.csv'
    >>> get_most_recent_filename("/nonexistent_directory", "file_", ".txt")
    'Directory not found: [/nonexistent_directory]'
    """
    # and here goes the function logic ...    

ps; this follows the numpy docstring conventions

0

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
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.