Python Language Comments and Documentation Programmatically accessing docstrings

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Docstrings are - unlike regular comments - stored as an attribute of the function they document, meaning that you can access them programmatically.

An example function

def func():
    """This is a function that does nothing at all"""
    return

The docstring can be accessed using the __doc__ attribute:

print(func.__doc__)

This is a function that does nothing at all

help(func)

Help on function func in module __main__:

func()

     This is a function that does nothing at all

Another example function

function.__doc__ is just the actual docstring as a string, while the help function provides general information about a function, including the docstring. Here's a more helpful example:

def greet(name, greeting="Hello"):
    """Print a greeting to the user `name`

    Optional parameter `greeting` can change what they're greeted with."""
    
    print("{} {}".format(greeting, name))
help(greet)

Help on function greet in module __main__:

greet(name, greeting='Hello')

    Print a greeting to the user name
    Optional parameter greeting can change what they're greeted with.

Advantages of docstrings over regular comments

Just putting no docstring or a regular comment in a function makes it a lot less helpful.

def greet(name, greeting="Hello"):
    # Print a greeting to the user `name`
    # Optional parameter `greeting` can change what they're greeted with.
    
    print("{} {}".format(greeting, name))
print(greet.__doc__)

None

help(greet)

Help on function greet in module main:

greet(name, greeting='Hello')



Got any Python Language Question?