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.

Answer from Rahul Gupta on Stack Overflow
🌐
Python
peps.python.org › pep-0257
PEP 257 – Docstring Conventions | peps.python.org
Any indentation in the first line of the docstring (i.e., up to the first newline) is insignificant and removed. Relative indentation of later lines in the docstring is retained. Blank lines should be removed from the beginning and end of the docstring. Since code is much more precise than words, here is an implementation of the algorithm:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-docstrings
Python Docstrings - GeeksforGeeks
September 19, 2025 - Docstrings (Documentation Strings) are special strings used to document Python code. They provide a description of what a module, class, function or method does. Declared using triple quotes (' ' ' or " " "). Written just below the definition ...
Discussions

Python docstrings and inline code; meaning of the ">>>" syntax - Stack Overflow
I have some experience in Python but only recently came across extensive usage of docstrings. I'm going through the Financial Market Simulator (FMS) source code, and when I open it in PyCharm I see... More on stackoverflow.com
🌐 stackoverflow.com
coding style - What are the most common Python docstring formats? - Stack Overflow
Personally I feel such a long docstring is better located in the documentation, not the source code, if it is so long they end up impeding readability of the module. 2019-01-07T16:41:10.083Z+00:00 ... It's Python; anything goes. Consider how to publish your documentation. More on stackoverflow.com
🌐 stackoverflow.com
Propper way to write DocStrings
There's this https://peps.python.org/pep-0257/ More on reddit.com
🌐 r/learnpython
5
1
January 5, 2023
Do short functions need docstrings?
If you write a function that is 1 or 2 lines long, does it still need a docstring? If so, what needs to be in the docstring? probably. depending on the tools used the docstring can become important. at most.. it doesn't hurt.. and takes like few seconds to do it... so .. if not the functions/methods .. at least the class. almost all the time, when i go looking into packages and find what i'm looking for .. they have wonderful descriptions of the classes .. it is incredibly helpful to try and understand what the creator of the code wanted to do . i find them particularly useful. More on reddit.com
🌐 r/learnpython
3
1
July 31, 2023
🌐
DataCamp
datacamp.com › tutorial › docstrings-python
Python Docstrings Tutorial : Examples & Format for Pydoc, Numpy, Sphinx Doc Strings | DataCamp
February 14, 2025 - Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition. Unlike regular comments, which explain individual ...
🌐
Programiz
programiz.com › python-programming › docstrings
Python Docstrings (With Examples)
As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code.
🌐
Pandas
pandas.pydata.org › docs › development › contributing_docstring.html
pandas docstring guide — pandas 3.0.2 documentation
A Python docstring is a string used to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.
🌐
Real Python
realpython.com › documenting-python-code
Documenting Python Code: A Complete Guide – Real Python
December 21, 2023 - Why Documenting Your Code Is So Important: An introduction to documentation and its importance · Commenting vs Documenting Code: An overview of the major differences between commenting and documenting, as well as the appropriate times and ways to use commenting · Documenting Your Python Code Base Using Docstrings: A deep dive into docstrings for classes, class methods, functions, modules, packages, and scripts, as well as what should be found within each one
Top answer
1 of 3
27

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.

2 of 3
5

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.

Find elsewhere
🌐
Dataquest
dataquest.io › blog › documenting-in-python-with-docstrings
Tutorial: Documenting in Python with Docstrings
December 13, 2024 - Sometimes they aren't necessary, and a small code comment may suffice (or even no comment at all). Assume that the developer has some basic knowledge of Python. Docstrings shouldn't explain how the function works under the hood but, rather, how to use it. Sometimes, it may be necessary to explain the inner mechanism of a piece of code, so use code comments for that.
🌐
Real Python
realpython.com › how-to-write-docstrings-in-python
How to Write Docstrings in Python – Real Python
June 19, 2025 - Learn to write effective Python docstrings that clearly and professionally document your code using best practices and built-in conventions.
🌐
Wikipedia
en.wikipedia.org › wiki › Docstring
Docstring - Wikipedia
December 19, 2025 - In Python, a docstring is a string literal that follows a module, class or function definition. It must be nothing but a string literal, not any other kind of expression. The docstring is accessible via the associated code element's __doc__ attribute and the help function.
🌐
Readthedocs
sphinxcontrib-napoleon.readthedocs.io › en › latest › example_google.html
Example Google Style Python Docstrings — napoleon 0.7 documentation
Attributes: msg (str): Human readable string describing the exception. code (int): Exception error code. """ def __init__(self, msg, code): self.msg = msg self.code = code class ExampleClass(object): """The summary line for a class docstring should fit on one line.
🌐
Tutorialspoint
tutorialspoint.com › python › python_docstrings.htm
Python - Docstrings
In Python, docstrings are a way of documenting modules, classes, functions, and methods. They are written within triple quotes (""" """) and can span multiple lines. Docstrings serve as convenient way of associating documentation with Python code.
🌐
Mimo
mimo.org › glossary › python › docstrings
Mimo: The coding platform you need to learn Web Development, Python, and more.
Can appear anywhere in the code. Use the # symbol before the text. ... Document modules, classes, and functions. Are accessible at runtime through help(). Go right after the definition line of a function, class, or module. Use triple quotes to enclose the text.
🌐
Medium
medium.com › jit-team › documenting-python-code-with-docstrings-b999ee164ff2
Documenting Python code with docstrings | by Adam Czapski | Jit Team | Medium
September 14, 2022 - For example, the following code has a docstring that explains what the code does: In this example, the docstring explains what the compute_average function does. This is important, because it means that someone reading the code will not have to guess the purpose of the function.
🌐
Google
google.github.io › styleguide › pyguide.html
Google Python Style Guide
No: Python("Why are you hiding your eyes?") Gollum('The lint. It burns. It burns us.') Gollum("Always the great lint. Watching. Watching.") Prefer """ for multi-line strings rather than '''. Projects may choose to use ''' for all non-docstring multi-line strings if and only if they also use ' for regular strings. Docstrings must use """ regardless. Multi-line strings do not flow with the indentation of the rest of the program.
🌐
Zero To Mastery
zerotomastery.io › blog › python-docstring
Beginner's Guide to Python Docstrings (With Code Examples) | Zero To Mastery
September 27, 2024 - For example, if you want to access the docstring of a function, you can use Python’s help() function: ... Help on function add_numbers in module __main__: add_numbers(x, y) This function takes two numbers and returns their sum. With docstrings, you’re making your code not only functional but also easy for others to understand—whether they’re running it or maintaining it.
Top answer
1 of 6
1389

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

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

2 of 6
354

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
🌐
Lsst
developer.lsst.io › v › DM-5063 › docs › py_docs.html
Documenting Python Code — LSST DM Developer Guide latest documentation
Docstrings are the public specification of our Python API. By commenting our code internally with hash marks (#).
🌐
Note.nkmk.me
note.nkmk.me › home › python
Python Docstring Formats (Styles) and Examples | note.nkmk.me
August 26, 2023 - For example, PyCharm, an integrated development environment for Python, supports all three styles. Specify types with docstrings | PyCharm Documentation ... def func_rest(param1, param2): """Summary line. :param param1: Description of param1 :type param1: int :param param2: Description of param2 :type param2: str :returns: Description of return value :rtype: bool """ return True ... For example, the reST style is used in Requests. The following is an actual code example.
🌐
iO Flood
ioflood.com › blog › python-docstring
Python Docstring Usage Guide (With Examples)
December 11, 2023 - For a more advanced understanding ... World!'""" print('Hello, World!') ... A Python Docstring is a string literal that you write as the first statement in a module, function, class, or method definition....