The statements written with >>> in the docstrings are doctests.
It lets you test your code by running examples embedded in the documentation and verifying that they produce the expected results. It parses the help text to find examples, runs them and then compares the output text against the expected value.
In your case, PyCharm has done the extra task of highlighting the python code in the docstrings. It won't affect your normal function execution so you don't need to worry about it.
Example:
Lets say I have a script named doctest_simple_addition in which i have written some doctests for add() function where some test cases gives proper output and some raises an exception. Then i can verify that my function produces the expected results by running those doctests.
doctest_simple_addition.py
def add(a,b):
"""
>>> add(1, 2)
3
>>> add(5, 3)
8
>>> add('a', 1)
Traceback (most recent call last):
...
TypeError: cannot concatenate 'str' and 'int' objects
"""
return a + b
To run the doctests, use doctest as the main program via the -m option to the interpreter. Usually, no output is produced while the tests are running. You can add the -v option and doctest will then print a detailed log of what it’s trying with a summary at the end.
Doctest looks for lines beginning with the interpreter prompt, >>>, to find the beginning of a test case. The test case is ended by a blank line, or by the next interpreter prompt.
$ python -m doctest -v doctest_simple_addition.py
Trying:
add(1, 2)
Expecting:
3
ok
Trying:
add(5, 3)
Expecting:
8
ok
Trying:
add('a', 1)
Expecting:
Traceback (most recent call last):
...
TypeError: cannot concatenate 'str' and 'int' objects
ok
1 items had no tests:
doctest_simple_addition
1 items passed all tests:
3 tests in doctest_simple_addition.add
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
Note: When doctest sees a traceback header line (either Traceback (most recent call last): or Traceback (innermost last):, depending on the version of Python you are running), it skips ahead to find the exception type and message, ignoring the intervening lines entirely.
This is done because paths in a traceback depend on the location where a module is installed on the filesystem on a given system and it would be impossible to write portable tests as the path would change from system to system.
Python docstrings and inline code; meaning of the ">>>" syntax - Stack Overflow
coding style - What are the most common Python docstring formats? - Stack Overflow
Propper way to write DocStrings
Do short functions need docstrings?
Videos
The statements written with >>> in the docstrings are doctests.
It lets you test your code by running examples embedded in the documentation and verifying that they produce the expected results. It parses the help text to find examples, runs them and then compares the output text against the expected value.
In your case, PyCharm has done the extra task of highlighting the python code in the docstrings. It won't affect your normal function execution so you don't need to worry about it.
Example:
Lets say I have a script named doctest_simple_addition in which i have written some doctests for add() function where some test cases gives proper output and some raises an exception. Then i can verify that my function produces the expected results by running those doctests.
doctest_simple_addition.py
def add(a,b):
"""
>>> add(1, 2)
3
>>> add(5, 3)
8
>>> add('a', 1)
Traceback (most recent call last):
...
TypeError: cannot concatenate 'str' and 'int' objects
"""
return a + b
To run the doctests, use doctest as the main program via the -m option to the interpreter. Usually, no output is produced while the tests are running. You can add the -v option and doctest will then print a detailed log of what it’s trying with a summary at the end.
Doctest looks for lines beginning with the interpreter prompt, >>>, to find the beginning of a test case. The test case is ended by a blank line, or by the next interpreter prompt.
$ python -m doctest -v doctest_simple_addition.py
Trying:
add(1, 2)
Expecting:
3
ok
Trying:
add(5, 3)
Expecting:
8
ok
Trying:
add('a', 1)
Expecting:
Traceback (most recent call last):
...
TypeError: cannot concatenate 'str' and 'int' objects
ok
1 items had no tests:
doctest_simple_addition
1 items passed all tests:
3 tests in doctest_simple_addition.add
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
Note: When doctest sees a traceback header line (either Traceback (most recent call last): or Traceback (innermost last):, depending on the version of Python you are running), it skips ahead to find the exception type and message, ignoring the intervening lines entirely.
This is done because paths in a traceback depend on the location where a module is installed on the filesystem on a given system and it would be impossible to write portable tests as the path would change from system to system.
Your intuition is correct, they are to be executed. But don't worry, they are doctest strings. They won't interfere with the normal execution of a module, so everything is fine. PyCharm is just being helpful by recognizing them.
Formats
Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.
Note that the reST is recommended by the PEP 287
There follows the main used formats for docstrings.
- Epytext
Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext format) to generate documentation.
Example:
"""
This is a javadoc style.
@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""
- reST
Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.
Example:
"""
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""
Google has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).
Example:
"""
This is an example of Google style.
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
Even more examples
- Numpydoc
Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx.
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
Converting/Generating
It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.
Note: The examples are taken from the Pyment documentation
The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:
def square_root(n):
"""Calculate the square root of a number.
Args:
n: the number to get the square root of.
Returns:
the square root of n.
Raises:
TypeError: if n is not a number.
ValueError: if n is negative.
"""
pass
I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:
def add_value(self, value):
"""Add a new value.
Args:
value (str): the value to add.
"""
pass