The Sphinx extension sphinx.ext.doctest
makes it straightforward to ensure that your documentation is up to date. At the same time, the matplotlib.sphinxext.plot_directive
extension makes it straightforward to auto-generate figures as part of your documentation.
In my situation, I would like to combine the best of both extensions and
- perform some slow calculation,
- check the results using doctest,
- plot the result.
That is, something similar to the below:
>>> import time
>>> def make_result():
... time.sleep(100)
... return [3, 4]
>>> result = make_result()
>>> print(result)
[3, 4]
.. plot::
>>> import matplotlib.pyplot as plt
>>> plt.plot(result)
>>> plt.show()
As it stands, this won't quite work since the plot directive does not have the context of the previous doctest block available. Moreover, using the "context" option of the plot directive doesn't seem quite sufficient as it gets rid of the doctest, and means that I will not have the context available for future non-plot-directive blocks.
So my question is:
What's the best way of combining these two operations, the assertion and the plot, while still getting the assertion run as a doctest, and without running the slow operation twice, and ensuring that the variables set in the doctest part of the code remains available for the rest of the document?
The best workaround I have is the following which works, but requires you to run the doctests before make html
, and produces annoying warnings in the doctest run when the image has not been generated yet:
>>> import time
>>> def make_result():
... time.sleep(100)
... return [3, 4]
>>> result = make_result()
>>> print(result)
[3, 4]
>>> import matplotlib.pyplot as plt
>>> plt.plot(result)
>>> plt.savefig('result.png')
.. image:: result.png