Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

docstring
python

What is a Python docstring?

Educative Answers Team

The Python docstrings provide a suitable way of associating documentation with:

  • Python modules
  • Python functions
  • Python classes

It is a specified document for the written code. Unlike conventional code comments, the doctoring should describe what a function does, not how it works.

svg viewer

The docstrings are declared using triple double quotes.

svg viewer

Accessing docstring

The docstring can be accessed using

  • __doc__ method of the object
  • help function

The __doc__ method is only used for primitive datatypes.


Example of a one-line docstring

In the code below, a single line docstring is used:

def hello_world(): 
    """Demonstrating docstring."""
   
    return None

# printing using __doc__ method 
print "Using __doc__ method:"
print hello_world.__doc__ 

# printing using help function 
print "Using help function:"
help(hello_world)

Example of a multi-line docstring

In the code snippets below, the appropriate method for the multi-line docstring is shown in a function and in a class:

def hello_world(argument): 
    """ 
    Summary line. 
  
    Here comes description of a function. 
  
    Parameters: 
    argument (int): Description of argument 
  
    Returns: 
    int: Description of return value 
  
    """
  
    return argument 
  
# printing using __doc__ method 
print "Using __doc__ method:"
print hello_world.__doc__ 

# printing using help function 
print "Using help function:"
help(hello_world)
class complex_number: 
	""" 
	This is a class for mathematical operations on complex numbers. 
	
	Parameters: 
		real (int): The real part of complex number. 
		imag (int): The imaginary part of complex number. 
	"""

	def add(self, number): 
		""" 
		The function adds two complex numbers. 

		Parameters: 
			number (complex_number): The complex number to be added. 
		
		Returns: 
			ComplexNumber: A complex number which contains the sum. 
		"""

		re = self.real + num.real 
		im = self.imag + num.imag 

		return ComplexNumber(re, im) 

help(complex_number) # to access Class docstring 
help(complex_number.add) # to access method's docstring 

RELATED TAGS

docstring
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring