Engineering

Python Comments and Docstrings

By July 31, 2022 No Comments

There’s one special comment called a ‘shebang’ that python scripts can start

#! /usr/bin/env python3

Having this source code allows you execute the python file. First you need to make the file executable with the following chmod +x example.py to allow it to be invoked from command line without having to specify the interpreter to run it.

./example.py

If you have any issues finding python3, check your installed directory with

which python

Generic comments in code are simply a # in front of any comment or line. You can also add them to the end of a line. Comments should add clarity that is not obvious with your function or variable calls. Your code should be clear to read without comments but large blocks of code or complex logic could help future maintainers understand your work.

doWork(x) # your comment here for more detail that's not too redundant

You can add self documenting comments to your project with docstrings, triple quotes, “”” that expand multiple lines. The autoDocstring VS Extension can be installed to help you auto generate the bulk of the template automatically. Start by installing the extension into VS Code and then on a def function, add a return to get into the first line of the function and then triple quotes “””, you should see a pop-up that says Generate Docstring. Here’s an example

def hello(name:str):
    """Returns a hello + name string

    Args:
        name (str): the name you want to say hello to
    """
    print("hello " + name)


if __name__ == '__main__':
    hello("david")
David

Author David

More posts by David

Leave a Reply