Skip to content

Move from cbook._warn_external() to _api.warn_external() #19144

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 2 commits into from
Dec 18, 2020
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
14 changes: 7 additions & 7 deletions lib/matplotlib/_constrained_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import numpy as np

import matplotlib.cbook as cbook
from matplotlib import _api
import matplotlib.transforms as mtransforms

_log = logging.getLogger(__name__)
Expand Down Expand Up @@ -94,9 +94,9 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad,
gss.add(gs)
gss = list(gss)
if len(gss) == 0:
cbook._warn_external('There are no gridspecs with layoutgrids. '
'Possibly did not call parent GridSpec with the'
' "figure" keyword')
_api.warn_external('There are no gridspecs with layoutgrids. '
'Possibly did not call parent GridSpec with the'
' "figure" keyword')

for _ in range(2):
# do the algorithm twice. This has to be done because decorations
Expand All @@ -122,9 +122,9 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad,
_reposition_axes(fig, renderer, h_pad=h_pad, w_pad=w_pad,
hspace=hspace, wspace=wspace)
else:
cbook._warn_external('constrained_layout not applied because '
'axes sizes collapsed to zero. Try making '
'figure larger or axes decorations smaller.')
_api.warn_external('constrained_layout not applied because '
'axes sizes collapsed to zero. Try making '
'figure larger or axes decorations smaller.')
_reset_margins(fig)


Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ def frame_format(self, frame_format):
if frame_format in self.supported_formats:
self._frame_format = frame_format
else:
cbook._warn_external(
_api.warn_external(
f"Ignoring file format {frame_format!r} which is not "
f"supported by {type(self).__name__}; using "
f"{self.supported_formats[0]} instead.")
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/artist.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,8 +901,7 @@ def set_rasterized(self, rasterized):
rasterized : bool
"""
if rasterized and not hasattr(self.draw, "_supports_rasterization"):
cbook._warn_external(
"Rasterization of '%s' will be ignored" % self)
_api.warn_external(f"Rasterization of '{self}' will be ignored")

self._rasterized = rasterized

Expand Down
13 changes: 6 additions & 7 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4722,9 +4722,8 @@ def reduce_C_function(C: array) -> float
# Set normalizer if bins is 'log'
if bins == 'log':
if norm is not None:
cbook._warn_external("Only one of 'bins' and 'norm' "
"arguments can be supplied, ignoring "
"bins={}".format(bins))
_api.warn_external("Only one of 'bins' and 'norm' arguments "
f"can be supplied, ignoring bins={bins}")
else:
norm = mcolors.LogNorm()
bins = None
Expand Down Expand Up @@ -5436,9 +5435,9 @@ def _pcolorargs(self, funcname, *args, shading='flat', **kwargs):
try:
_api.check_in_list(_valid_shading, shading=shading)
except ValueError as err:
cbook._warn_external(f"shading value '{shading}' not in list of "
f"valid values {_valid_shading}. Setting "
"shading='auto'.")
_api.warn_external(f"shading value '{shading}' not in list of "
f"valid values {_valid_shading}. Setting "
"shading='auto'.")
shading = 'auto'

if len(args) == 1:
Expand Down Expand Up @@ -5523,7 +5522,7 @@ def _interp_grid(X):
if np.shape(X)[1] > 1:
dX = np.diff(X, axis=1)/2.
if not (np.all(dX >= 0) or np.all(dX <= 0)):
cbook._warn_external(
_api.warn_external(
f"The input coordinates to {funcname} are "
"interpreted as cell centers, but are not "
"monotonically increasing or decreasing. "
Expand Down
20 changes: 10 additions & 10 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def __call__(self, *args, data=None, **kwargs):
label_namer_idx = 1
else:
if replaced[1] is not args[1]: # case 2a)
cbook._warn_external(
_api.warn_external(
f"Second argument {args[1]!r} is ambiguous: could "
f"be a format string but is in 'data'; using as "
f"data. If it was intended as data, set the "
Expand Down Expand Up @@ -2456,7 +2456,7 @@ def margins(self, *margins, x=None, y=None, tight=True):

if x is None and y is None:
if tight is not True:
cbook._warn_external(f'ignoring tight={tight!r} in get mode')
_api.warn_external(f'ignoring tight={tight!r} in get mode')
return self._xmargin, self._ymargin

if tight is not None:
Expand Down Expand Up @@ -3442,19 +3442,19 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False,
# so only grab the limits if we really need them.
old_left, old_right = self.get_xlim()
if left <= 0:
cbook._warn_external(
_api.warn_external(
'Attempted to set non-positive left xlim on a '
'log-scaled axis.\n'
'Invalid limit will be ignored.')
left = old_left
if right <= 0:
cbook._warn_external(
_api.warn_external(
'Attempted to set non-positive right xlim on a '
'log-scaled axis.\n'
'Invalid limit will be ignored.')
right = old_right
if left == right:
cbook._warn_external(
_api.warn_external(
f"Attempting to set identical left == right == {left} results "
f"in singular transformations; automatically expanding.")
reverse = left > right
Expand Down Expand Up @@ -3768,19 +3768,19 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False,
# so only grab the limits if we really need them.
old_bottom, old_top = self.get_ylim()
if bottom <= 0:
cbook._warn_external(
_api.warn_external(
'Attempted to set non-positive bottom ylim on a '
'log-scaled axis.\n'
'Invalid limit will be ignored.')
bottom = old_bottom
if top <= 0:
cbook._warn_external(
_api.warn_external(
'Attempted to set non-positive top ylim on a '
'log-scaled axis.\n'
'Invalid limit will be ignored.')
top = old_top
if bottom == top:
cbook._warn_external(
_api.warn_external(
f"Attempting to set identical bottom == top == {bottom} "
f"results in singular transformations; automatically "
f"expanding.")
Expand Down Expand Up @@ -4067,7 +4067,7 @@ def _set_view_from_bbox(self, bbox, direction='in',
xzc + xwidth/2./scl, yzc + ywidth/2./scl]
elif len(bbox) != 4:
# should be len 3 or 4 but nothing else
cbook._warn_external(
_api.warn_external(
"Warning in _set_view_from_bbox: bounding box is not a tuple "
"of length 3 or 4. Ignoring the view change.")
return
Expand Down Expand Up @@ -4211,7 +4211,7 @@ def format_deltas(key, dx, dy):
result = (mtransforms.Bbox(newpoints)
.transformed(p.trans_inverse))
except OverflowError:
cbook._warn_external('Overflow while panning')
_api.warn_external('Overflow while panning')
return
else:
return
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/axes/_secondary_axes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import numpy as np

from matplotlib import _api
import matplotlib.cbook as cbook
import matplotlib.docstring as docstring
import matplotlib.ticker as mticker
from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator
Expand Down Expand Up @@ -246,7 +245,7 @@ def set_aspect(self, *args, **kwargs):
Secondary axes cannot set the aspect ratio, so calling this just
sets a warning.
"""
cbook._warn_external("Secondary axes can't set the aspect ratio")
_api.warn_external("Secondary axes can't set the aspect ratio")

def set_color(self, color):
"""
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1390,9 +1390,9 @@ def grid(self, b=None, which='major', **kwargs):
raise ValueError(
"'b' and 'visible' specify inconsistent grid visibilities")
if kwargs and not b: # something false-like but not None
cbook._warn_external('First parameter to grid() is false, '
'but line properties are supplied. The '
'grid will be enabled.')
_api.warn_external('First parameter to grid() is false, '
'but line properties are supplied. The '
'grid will be enabled.')
b = True
which = which.lower()
_api.check_in_list(['major', 'minor', 'both'], which=which)
Expand Down Expand Up @@ -1604,8 +1604,8 @@ def _set_formatter(self, formatter, level):
if (isinstance(formatter, mticker.FixedFormatter)
and len(formatter.seq) > 0
and not isinstance(level.locator, mticker.FixedLocator)):
cbook._warn_external('FixedFormatter should only be used together '
'with FixedLocator')
_api.warn_external('FixedFormatter should only be used together '
'with FixedLocator')

if level == self.major:
self.isDefault_majfmt = False
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -3546,7 +3546,7 @@ def show(cls, *, block=None):
try:
manager.show() # Emits a warning for non-interactive backend.
except NonGuiException as exc:
cbook._warn_external(str(exc))
_api.warn_external(str(exc))
if cls.mainloop is None:
return
if block is None:
Expand Down
11 changes: 5 additions & 6 deletions lib/matplotlib/backend_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,8 @@ def update_keymap(self, name, key, *args):
key = [key]
for k in key:
if k in self._keys:
cbook._warn_external('Key %s changed from %s to %s' %
(k, self._keys[k], name))
_api.warn_external(
f'Key {k} changed from {self._keys[k]} to {name}')
self._keys[k] = name

def remove_tool(self, name):
Expand Down Expand Up @@ -267,8 +267,8 @@ def add_tool(self, name, tool, *args, **kwargs):
raise ValueError('Impossible to find class for %s' % str(tool))

if name in self._tools:
cbook._warn_external('A "Tool class" with the same name already '
'exists, not added')
_api.warn_external('A "Tool class" with the same name already '
'exists, not added')
return self._tools[name]

tool_obj = tool_cls(self, name, *args, **kwargs)
Expand Down Expand Up @@ -437,7 +437,6 @@ def get_tool(self, name, warn=True):
return name
if name not in self._tools:
if warn:
cbook._warn_external("ToolManager does not control tool "
"%s" % name)
_api.warn_external(f"ToolManager does not control tool {name}")
return None
return self._tools[name]
2 changes: 1 addition & 1 deletion lib/matplotlib/backend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class ToolBase:
"""

def __init__(self, toolmanager, name):
cbook._warn_external(
_api.warn_external(
'The new Tool classes introduced in v1.5 are experimental; their '
'API (including names) will likely change in future versions.')
self._name = name
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,12 @@ def check_trapped(x):
}
for k in info:
if k not in keywords:
cbook._warn_external(f'Unknown infodict keyword: {k!r}. '
f'Must be one of {set(keywords)!r}.')
_api.warn_external(f'Unknown infodict keyword: {k!r}. '
f'Must be one of {set(keywords)!r}.')
elif not keywords[k](info[k]):
cbook._warn_external(f'Bad value for infodict keyword {k}. '
f'Got {info[k]!r} which is not '
f'{keywords[k].text_for_warning}.')
_api.warn_external(f'Bad value for infodict keyword {k}. '
f'Got {info[k]!r} which is not '
f'{keywords[k].text_for_warning}.')
if 'Trapped' in info:
info['Trapped'] = Name(info['Trapped'])

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ def draw_image(self, gc, x, y, im, transform=None):
return

if not os.path.exists(getattr(self.fh, "name", "")):
cbook._warn_external(
_api.warn_external(
"streamed pgf-code does not support raster graphics, consider "
"using the pgf-to-pdf option.")

Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/qt_editor/_formlayout.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
import logging
from numbers import Integral, Real

from matplotlib import cbook, colors as mcolors
from matplotlib import _api, colors as mcolors
from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore

_log = logging.getLogger(__name__)
Expand Down Expand Up @@ -95,7 +95,7 @@ def to_qcolor(color):
try:
rgba = mcolors.to_rgba(color)
except ValueError:
cbook._warn_external('Ignoring invalid color %r' % color)
_api.warn_external(f'Ignoring invalid color {color!r}')
return qcolor # return invalid QColor
qcolor.setRgbF(*rgba)
return qcolor
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/bezier.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import numpy as np

from matplotlib import _api, cbook
from matplotlib import _api


# same algorithm as 3.8's math.comb
Expand Down Expand Up @@ -478,7 +478,7 @@ def get_parallels(bezier2, width):
cmx - c2x, cmy - c2y)

if parallel_test == -1:
cbook._warn_external(
_api.warn_external(
"Lines do not intersect. A straight line is used instead.")
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
cos_t2, sin_t2 = cos_t1, sin_t1
Expand Down
7 changes: 3 additions & 4 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@

import matplotlib
from matplotlib import _api, _c_internal_utils
from matplotlib._api import (
warn_external as _warn_external, classproperty as _classproperty)
from matplotlib._api import classproperty as _classproperty
from matplotlib._api.deprecation import (
deprecated, warn_deprecated,
_deprecate_method_override, _deprecate_privatize_attribute,
Expand Down Expand Up @@ -348,8 +347,8 @@ def _local_over_kwdict(
if out is None:
out = kwarg_val
else:
_warn_external('"%s" keyword argument will be ignored' % key,
warning_cls)
_api.warn_external(f'"{key}" keyword argument will be ignored',
warning_cls)
return out


Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@
def _set_ticks_on_axis_warn(*args, **kw):
# a top level function which gets put in at the axes'
# set_xticks and set_yticks by ColorbarBase.__init__.
cbook._warn_external("Use the colorbar set_ticks() method instead.")
_api.warn_external("Use the colorbar set_ticks() method instead.")


class _ColorbarAutoLocator(ticker.MaxNLocator):
Expand Down Expand Up @@ -721,7 +721,7 @@ def set_ticklabels(self, ticklabels, update_ticks=True):
if update_ticks:
self.update_ticks()
else:
cbook._warn_external("set_ticks() must have been called.")
_api.warn_external("set_ticks() must have been called.")
self.stale = True

def minorticks_on(self):
Expand Down
Loading