‘Python comment block’ and similarly ‘Python docstring’ both are very useful features of python language, as comments are very common in other programming languages too. Following text will also explain the types of python comment block e.g python multiline comment. But now as usual, starts from basics of comments.

What is a comment?

There are 2 main purposes of comments

  1. To explain what the code is supposed to do and how you make it work.
  2. To enforce the interpreter to ignore the already written code in application.

In case if you come back to your code after a long time, comments are also very helpful in understanding the code. And for other people too, who are new to your block of code. 

Python comment block

While writing a program or block of code in python comment block starts by a pound(#) sign. After writing a # that specific line becomes python comment block. Coder can write any instruction or guided text in that line, Its all text will be ignored by the python interpreter.

Python comment block has 2 options, which are following:

Python single-line comment

Normally a python comment block has only one line. As we do write in the following code

>>>first_name = 'john'

>>>last_name = 'doe'

#This code will append the first name and last name

>>>print(first_name +" "+last_name)

While using the single line comment style, you can write multiple single line comments too. e.g

>>>first_operand = 5

>>>second_operand = 12

#We have 2 operands to calculate the answer

#Now it will add both operand numbers

>>>result = first_operand + second_operand

#Now print the result

>>>print(result)

Python multiline comment

In python if the requirement to write a multiline comment but not as multiple single line comments. The way to achieve the goal is to write python string as a docstring comment. i.e use triple-single or triple-double quotes”. Here is the detail to use docstring

Python Docstring

Docstring style comment is a more famous and conventional way of python comments. It is also a very convenient way of attaching the documentation to a python function, python class or a python module. The basic purpose of python docstring is to define a comment about the functional reason(what it do) of a function, class or a module.

To use the python docstring, there are 2 steps

  • Declaring a python docstring
  • Accessing a python docstring

Declaring a python docstring

Syntax to write or attach a python docstring to a function, class or a module is to defines it in the very next line of their declaration. Docstring comment can be define in one line or it can be a multi liner. All possible declarations are recommended to have a docstring comment.

Docstring can be define using triple-single quotes or triple-double quotes

>>> def sum(x, y):

      """Returns added result of both arguments(x and y)."""
      return a+b

>>> def grossSalaryPerWeekFormula(perHourPay, hoursPerDay, overTimePerHour, overTimeHours):
       """
       First, calculate regular pay: perHourPay x hoursPerDay x 5 
       = Per week regular income

       Then, calculate overtime payoverTimePerHour x 
       overTimeHours = Per week overtime income

       The total gross pay for the weekly pay period is = Per 
       week regular income  + Per week overtime income
       """
       perWeekRegularIncome  = perHourPay x hoursPerDay x 5
       perWeekOvertimeIncome = payoverTimePerHour x overTimeHours 
       return perWeekRegularIncome  + perWeekOvertimeIncome

Accessing a python docstring

A declared docstring comment can be accessed by using python’s build-in help function or  __doc__ method.

Unlike the normal conventional python comment block docstring attached with a python module also available at runtime. That means at anytime a attached docstring can be printed.

File name is samplemod.py so the module name will be samplemod

"""This is a python comment testing module."""
def func1(x):
    """This is the docstring testing function."""
    return 2 * x

Using doc function

>>> import samplemod
>>> samplemod.__doc__
'This is a python comment testing module.'

>>> samplemod.func1.__doc__
'This is the docstring testing function.'

Using help function

>>> import samplemod
>>> help(samplemod)

Help on module sample1:

NAME
    samplemod - This is a python comment testing module.

FUNCTIONS
    func1(x)
        This is the docstring testing function.

FILE
    /Users/laptopworld/dev/samplemod.py

Python has multiple popular docstring formats

  • Sphinx style
  • Numpy style

Sphinx style

Sphinx is the traditional style of python documentation, it was introduced specifically for the python documentation purpose. Its text structure very similar to Markdown language.

>>> def isEvenNumber(x):
    '''
    This function takes a number as an argument
    :apply an operation on it
    :print whether the number is even or not
    '''
    if x % 2 == 0:
        print("Number "+ x + " is an even number")
    else:
        print("Number "+ x + " is not an even number")

Numpy style

Numpy style is very verbose style of documentation. It gives very detailed info of target. Numpy style documentation is more recommended for complex projects

 
def PythagoreanTheorem(perpendicular, base):
    """
    The theorem can be written as an equation relating the 
    lengths of the sides a, b and c, often called the 
    'Pythagorean equation'
        
    Parameters
    ----------
    param1 : int
        param1 is length of perpendicular
    param2 : int
        param2 is length of base
    param3 : int
        param3 is length of hypotenuse
    Returns
    -------
    int
        If c denotes the length of the hypotenuse and a and b 
        denote the lengths of the other two sides, the 
        Pythagorean theorem can be expressed as the Pythagorean 
        equation:
        hypotenuse * hypotenuse = perp * perp + base * base
    """

    return sqrt(perp * perp + base * base)


There are many other styles too, like ‘Google style’ but these were the most famous ones.

One thought on “Python Comment block & Python docstring”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.