previous
Python Rules Of Coding: String literals
Python docstring (documentation string) is a string literal and it can be used in any code block, i.e., the class, module, function, method definition. It provides us a handy way of attaching the relevant documentation within the code block. It describes the source code.
We generally use comments for documentation of a single line code, statement, and expressions which are usually small and not so explanatory.
Remember, this does not diminish the importance of comments use.
Docstrings are a descriptive text and better for easily understanding the functionality, the purpose of the code block.
When a programmer creates class, module, function, he/she associates the documentation for another developer to know what the purpose or what does of that class, module, function.
So that other developer who wishes to contribute to that project can easily grasp the understanding of this code block without having to read the details of the implementation.
We can use Python documentation generators like Sphinx to generate HTML documentation automatically from Docstrings.
The source code documentation (Docstrings) can be accessed using the built-in __doc__attribute or using the help function.
As PEP 257 -- Docstring Conventions, we should use
" " " triple double quotes " " " in docstrings.
r " " " raw triple double quotes " " " escape backslashes in docstrings.
u" " " Unicode triple quoted strings" " " for unicode docstrings.
We are familiar with two forms of docstrings.
class Sensor:
def __init__(self, calc=0.0):
“ “ “Initialize the Sensor object with the given warmth value.” “ “
self.set_temperature(Calc)
return
Notes from PEP 257 -- Docstring Conventions :
def square(b):
“ “ “ Returned argument b is squared.” “ “
return b**b
print(square.__doc__) #using __doc__ attribute
Returned argument b is squared.
We can also access to the docstring using the built-in help function
def square(b):
“ “ “ Returned argument b is squared.” “ “
return b**b
help(square) # using help function
Help on function square in module __main__:
square(b)
Returned argument a is squared.
The form of multi-line docstrings is the same as a one-line docstring, but it is a more elaborate description.
def my_func(dev1):
"""
Summary line.
Elaborated description of function.
Parameters:
dev1(int): Description of dev1
Returns:
int: Description of return value
"""
return dev1
print my_func.__doc
Summary line.
Elaborated description of function.
Parameters:
dev1(int): Description of dev1
Returns:
int: Description of return value
______________________