Member-only story
Docstrings in Python: An Introduction
Docstrings in Python are a useful feature, present for a long time, but often underused. In brief, these are descriptions of an object in Python. This object can be a module, a class, a function or a method. Can we use them on packages? No. On instances? No. They are available only on these four object types. Docstrings are a short version of document strings, and they are exactly that: strings that are used as documentation, attached to objects. They are introduced by PEP257, called Docstring Conventions, and are defined as a string literal that comes after line that defines any of these objects. String literal, as you know, can be defined with one single or double quotes, or triple single/double quotes. You may expect that you can use any of those for docstrings, and theoretically, you will get the result you want. But, PEP 257 recommends using triple double quotes, even for one line docstrings.
Why not use comments, you may wonder? I will show you soon. Let’s create a simple function, hello and add a docstring.
def hello():
"""Simple function that prints a Hello, World! Greeting"""
print("Hello, World!")If we placed comment, we will be able to see it when we read code, but there will be no way to use it when we use function. With docstring, it becomes attached to a function and we can obtain it using the program…







