Skip to content

Commit 87442b2

Browse files
committed
Simplify _api.warn_external on Python 3.12+
Python 3.12 added the `skip_file_prefixes` argument, which essentially does what this helper function does for us. Technically, I think the old implementation would set the stack level to the tests, if called in one, but this one doesn't. However, that shouldn't be a problem, as either 1) warnings are errors, or 2), we catch the warning with `pytest.warns` and don't see the stack level.
1 parent 9f49b07 commit 87442b2

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

lib/matplotlib/_api/__init__.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -366,16 +366,22 @@ def warn_external(message, category=None):
366366
warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
367367
etc.).
368368
"""
369-
frame = sys._getframe()
370-
for stacklevel in itertools.count(1):
371-
if frame is None:
372-
# when called in embedded context may hit frame is None
373-
break
374-
if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))",
375-
# Work around sphinx-gallery not setting __name__.
376-
frame.f_globals.get("__name__", "")):
377-
break
378-
frame = frame.f_back
379-
# preemptively break reference cycle between locals and the frame
380-
del frame
381-
warnings.warn(message, category, stacklevel)
369+
kwargs = {}
370+
if sys.version_info[:2] >= (3, 12):
371+
kwargs['skip_file_prefixes'] = ('matplotlib', 'mpl_toolkits')
372+
else:
373+
frame = sys._getframe()
374+
for stacklevel in itertools.count(1):
375+
if frame is None:
376+
# when called in embedded context may hit frame is None
377+
kwargs['stacklevel'] = stacklevel
378+
break
379+
if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))",
380+
# Work around sphinx-gallery not setting __name__.
381+
frame.f_globals.get("__name__", "")):
382+
kwargs['stacklevel'] = stacklevel
383+
break
384+
frame = frame.f_back
385+
# preemptively break reference cycle between locals and the frame
386+
del frame
387+
warnings.warn(message, category, **kwargs)

0 commit comments

Comments
 (0)