📝 Docstring in Python

Documenting Code the Right Way

🔹 Definition

A docstring in Python is a special type of string used to document code. In simple words, it is a way to explain what a function, class, or module does so that anyone reading the code can understand it easily.

Docstrings are written inside triple quotes (""" """ or ''' ''') and are placed as the first statement in a function, class, or module.

Unlike comments, docstrings can be accessed at runtime. This makes them useful for automatic documentation tools. They improve readability, maintenance, and collaboration.

Article Algo

📌 Syntax of Docstring

For a function:

def function_name(parameters):
  """This is a docstring that describes the function"""
  # function body

For a class:

class ClassName:
  """This is a docstring for the class"""
  # class body

🧮 Example 1: Docstring in a Function

def add(a, b):
  """This function takes two numbers and returns their sum."""
  return a + b

print(add.__doc__)
Explanation

The text inside triple quotes is the docstring. add.__doc__ prints the docstring at runtime. This helps users understand the function without reading its logic.

🏫 Example 2: Docstring in a Class

class Student:
  """This class stores information about a student and their grades."""

  def __init__(self, name, grade):
    """Initializes the student with name and grade."""
    self.name = name
    self.grade = grade

print(Student.__doc__)
print(Student.__init__.__doc__)
Explanation

Docstrings can be written inside classes and methods. You can access class docstrings using ClassName.__doc__ and method docstrings using ClassName.method.__doc__.

🔑 Key Points to Remember

  • Docstrings describe the purpose of code
  • They are written using triple quotes
  • Accessible at runtime using __doc__
  • Useful for documentation tools

📌 Conclusion

Docstrings are an essential practice in Python. They make code readable, self-documented, and professional. Writing clear docstrings ensures that your code is easy to understand and maintain, even in the future.