Skip to content

Commit 19ca024

Browse files
committed
sphinx directive warning filter
1 parent e394940 commit 19ca024

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

lib/matplotlib/sphinxext/plot_directive.py

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@
7878
figure. This overwrites the caption given in the content, when the plot
7979
is generated from a file.
8080
81+
``:filter-warning:`` : str
82+
When specified, will ignore warnings that match the input string, which is
83+
a warnings filter `message regex <msg>`_ string.
84+
85+
.. _msg: https://docs.python.org/3/library/warnings.html#the-warnings-filter
86+
8187
Additionally, this directive supports all the options of the `image directive
8288
<https://docutils.sourceforge.io/docs/ref/rst/directives.html#image>`_,
8389
except for ``:target:`` (since plot will add its own target). These include
@@ -177,6 +183,7 @@
177183
import sys
178184
import textwrap
179185
import traceback
186+
import warnings
180187

181188
from docutils.parsers.rst import directives, Directive
182189
from docutils.parsers.rst.directives.images import Image
@@ -221,6 +228,10 @@ def _option_format(arg):
221228
return directives.choice(arg, ('python', 'doctest'))
222229

223230

231+
def _option_string(arg):
232+
return arg if arg.strip() else False
233+
234+
224235
def mark_plot_labels(app, document):
225236
"""
226237
To make plots referenceable, we need to move the reference from the
@@ -271,7 +282,8 @@ class PlotDirective(Directive):
271282
'context': _option_context,
272283
'nofigs': directives.flag,
273284
'caption': directives.unchanged,
274-
}
285+
'filter-warning': _option_string,
286+
}
275287

276288
def run(self):
277289
"""Run the plot directive."""
@@ -854,16 +866,20 @@ def run(arguments, content, options, state_machine, state, lineno):
854866

855867
# make figures
856868
try:
857-
results = render_figures(code=code,
858-
code_path=source_file_name,
859-
output_dir=build_dir,
860-
output_base=output_base,
861-
context=keep_context,
862-
function_name=function_name,
863-
config=config,
864-
context_reset=context_opt == 'reset',
865-
close_figs=context_opt == 'close-figs',
866-
code_includes=source_file_includes)
869+
with warnings.catch_warnings(record=True) as w:
870+
if msg := options.get('filter-warning', False):
871+
warnings.filterwarnings('ignore', message=msg)
872+
873+
results = render_figures(code=code,
874+
code_path=source_file_name,
875+
output_dir=build_dir,
876+
output_base=output_base,
877+
context=keep_context,
878+
function_name=function_name,
879+
config=config,
880+
context_reset=context_opt == 'reset',
881+
close_figs=context_opt == 'close-figs',
882+
code_includes=source_file_includes)
867883
errors = []
868884
except PlotError as err:
869885
reporter = state.memo.reporter

0 commit comments

Comments
 (0)