What is the proper way to comment functions in Python?

前端 未结 10 1582
情书的邮戳
情书的邮戳 2021-01-30 01:58

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

#########################################################
# Create         


        
相关标签:
10条回答
  • 2021-01-30 02:20

    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

    0 讨论(0)
  • 2021-01-30 02:20

    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.

    0 讨论(0)
  • 2021-01-30 02:21

    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.

    0 讨论(0)
  • 2021-01-30 02:24

    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
    0 讨论(0)
  • 2021-01-30 02:26

    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
     """
    
    0 讨论(0)
  • 2021-01-30 02:31

    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 讨论(0)
提交回复
热议问题