[파이썬] 함수의 docstring과 help() 함수

In Python, a docstring is a multi-line string that provides a description of a function, module, class, or method. It is used to document the purpose, arguments, and behavior of the code. Docstrings are surrounded by triple quotes (‘’’ ‘’’) and are placed immediately after the function, module, class, or method definition.

Using docstrings is good practice as it helps other developers understand your code and makes it easier to maintain and debug. Moreover, Python provides the built-in help() function that can be used to access the docstring of any object.

Let’s go through an example to understand how to use docstrings and the help() function effectively.

Example Function with Docstring

def calculate_circle_area(radius):
    """
    Calculate the area of a circle given its radius.
    
    Parameters:
    radius (float): The radius of the circle.
    
    Returns:
    float: The area of the circle.
    """
    return 3.14 * radius * radius

In the above example, the calculate_circle_area() function calculates the area of a circle based on its radius. The docstring provides a clear description of the purpose of the function, explains the parameter and return value, and shows the expected data types.

Using the help() function

To access the docstring of a function, module, class, or method, you can use the help() function in Python.

help(calculate_circle_area)

Running the above code will display the following output:

Help on function calculate_circle_area in module __main__:

calculate_circle_area(radius)
    Calculate the area of a circle given its radius.
    
    Parameters:
    radius (float): The radius of the circle.
    
    Returns:
    float: The area of the circle.

The help() function displays the docstring of the specified object, providing you with a quick reference to understand how the function or method works and what arguments it accepts.

Conclusion

Docstrings are an essential part of writing clean and maintainable code in Python. They provide documentation and help other developers understand how to use your code effectively. By using the help() function, you can quickly access docstrings and get information about any object in Python.

So, make it a habit to write descriptive docstrings for your functions, modules, classes, and methods, and leverage the help() function whenever you need to access the docstring of any object in Python. It will enhance code readability and collaboration, saving time and effort in the long run.