Skip to content

Automagically set the stacklevel on warnings. #11298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ def _plot_args_replacer(args, data):
except ValueError:
pass
else:
warnings.warn(
cbook._warn_external(
"Second argument {!r} is ambiguous: could be a color spec but "
"is in data; using as data. Either rename the entry in data "
"or use three arguments to plot.".format(args[1]),
RuntimeWarning, stacklevel=3)
RuntimeWarning)
return ["x", "y"]
elif len(args) == 3:
return ["x", "y", "c"]
Expand Down
22 changes: 20 additions & 2 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import glob
import gzip
import io
from itertools import repeat
import itertools
import locale
import numbers
import operator
Expand Down Expand Up @@ -1254,7 +1254,7 @@ def _compute_conf_interval(data, med, iqr, bootstrap):

ncols = len(X)
if labels is None:
labels = repeat(None)
labels = itertools.repeat(None)
elif len(labels) != ncols:
raise ValueError("Dimensions of labels and X must be compatible")

Expand Down Expand Up @@ -2032,3 +2032,21 @@ def _setattr_cm(obj, **kwargs):
delattr(obj, attr)
else:
setattr(obj, attr, orig)


def _warn_external(message, category=None):
"""
`warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib".

The original emitter of the warning can be obtained by patching this
function back to `warnings.warn`, i.e. ``cbook._warn_external =
warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
etc.).
"""
frame = sys._getframe()
for stacklevel in itertools.count(1):
if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.)",
frame.f_globals["__name__"]):
break
frame = frame.f_back
warnings.warn(message, category, stacklevel)