Skip to content

Fix various issues from SonarQube #23494

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 10 commits into from
Aug 3, 2022
1 change: 0 additions & 1 deletion doc/sphinxext/redirect_from.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ class RedirectFrom(Directive):
def run(self):
redirected_doc, = self.arguments
env = self.app.env
builder = self.app.builder
domain = env.get_domain('redirect_from')
current_doc = env.path2doc(self.state.document.current_source)
redirected_reldoc, _ = env.relfn2path(redirected_doc, current_doc)
Expand Down
7 changes: 2 additions & 5 deletions examples/event_handling/coords_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,8 @@

def on_move(event):
if event.inaxes:
# get the x and y pixel coords
x, y = event.x, event.y
ax = event.inaxes # the axes instance
print('data coords %f %f, pixel coords %f %f'
% (event.xdata, event.ydata, x, y))
print(f'data coords {event.xdata} {event.ydata},',
f'pixel coords {event.x} {event.y}')


def on_click(event):
Expand Down
6 changes: 3 additions & 3 deletions examples/event_handling/pick_event_demo2.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@
def onpick(event):

if event.artist != line:
return True
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes the return type and bool value of the return. Do we not actually use this return?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No event handlers use the return value; CallbackRegistry does not do anything with it.

return

N = len(event.ind)
if not N:
return True
return

figi, axs = plt.subplots(N, squeeze=False)
for ax, dataind in zip(axs.flat, event.ind):
Expand All @@ -47,7 +47,7 @@ def onpick(event):
transform=ax.transAxes, va='top')
ax.set_ylim(-0.5, 1.5)
figi.show()
return True


fig.canvas.mpl_connect('pick_event', onpick)

Expand Down
10 changes: 3 additions & 7 deletions examples/event_handling/pong_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def __init__(self, ax):
animated=False)
self.canvas.mpl_connect('key_press_event', self.on_key_press)

def draw(self, event):
def draw(self):
draw_artist = self.ax.draw_artist
if self.background is None:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
Expand Down Expand Up @@ -231,7 +231,7 @@ def draw(self, event):

self.background = None
self.ax.figure.canvas.draw_idle()
return True
return
puck.disp.set_offsets([[puck.x, puck.y]])
self.ax.draw_artist(puck.disp)

Expand All @@ -244,7 +244,6 @@ def draw(self, event):
plt.close()

self.cnt += 1
return True

def on_key_press(self, event):
if event.key == '3':
Expand Down Expand Up @@ -317,10 +316,7 @@ def on_redraw(event):
def start_anim(event):
canvas.mpl_disconnect(start_anim.cid)

def local_draw():
if animation.ax.get_renderer_cache():
animation.draw(None)
start_anim.timer.add_callback(local_draw)
start_anim.timer.add_callback(animation.draw)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is changing the semantics to call draw() unconditionally. I don't claim to understand why the original code did not draw if there is a renderer_cache, but we should now why it's been there and can now leave it out (@tacaswell you wrote this originally).

Semi-OT: This removes the only usage of Axes.get_renderer_cache, which is undocumented by the way. Do we still need to expose this? If yes, this needs documentation, if no we should deprecate it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect that this was a hedge to make sure we were actually drawn once before running because the draw method on Animation requires use Axes.draw_artist which in turn requires the Axes to have been drawn once to get a cached render.

However, we have made a lot of progress in pushing the caching of renderers into exactly 1 place and only access them via a function that will fabricate one if needed so I suspect we may no longer need this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See above: #23494 (comment)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #23202 for removal of the Axes.get_renderer_cache

start_anim.timer.start()
canvas.mpl_connect('draw_event', on_redraw)

Expand Down
15 changes: 7 additions & 8 deletions examples/misc/demo_agg_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class BaseFilter:
def get_pad(self, dpi):
return 0

def process_image(padded_src, dpi):
def process_image(self, padded_src, dpi):
raise NotImplementedError("Should be overridden by subclasses")

def __call__(self, im, dpi):
Expand Down Expand Up @@ -233,20 +233,19 @@ def drop_shadow_line(ax):
def drop_shadow_patches(ax):
# Copied from barchart_demo.py
N = 5
men_means = [20, 35, 30, 35, 27]
group1_means = [20, 35, 30, 35, 27]

ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars

rects1 = ax.bar(ind, men_means, width, color='r', ec="w", lw=2)
rects1 = ax.bar(ind, group1_means, width, color='r', ec="w", lw=2)

women_means = [25, 32, 34, 20, 25]
rects2 = ax.bar(ind + width + 0.1, women_means, width,
group2_means = [25, 32, 34, 20, 25]
rects2 = ax.bar(ind + width + 0.1, group2_means, width,
color='y', ec="w", lw=2)

# gauss = GaussianFilter(1.5, offsets=(1, 1))
gauss = DropShadowFilter(5, offsets=(1, 1))
shadow = FilteredArtistList(rects1 + rects2, gauss)
drop = DropShadowFilter(5, offsets=(1, 1))
shadow = FilteredArtistList(rects1 + rects2, drop)
ax.add_artist(shadow)
shadow.set_zorder(rects1[0].get_zorder() - 0.1)

Expand Down
2 changes: 1 addition & 1 deletion examples/misc/hyperlinks_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

fig = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['https://www.bbc.co.uk/news', 'https://www.google.com/', None])
s.set_urls(['https://www.bbc.com/news', 'https://www.google.com/', None])
fig.savefig('scatter.svg')

###############################################################################
Expand Down
1 change: 0 additions & 1 deletion examples/subplots_axes_and_figures/axes_zoom_effect.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ def connect_bbox(bbox1, bbox2,
bbox_patch2 = BboxPatch(bbox2, **prop_patches)

p = BboxConnectorPatch(bbox1, bbox2,
# loc1a=3, loc2a=2, loc1b=4, loc2b=1,
loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,
clip_on=False,
**prop_patches)
Expand Down
3 changes: 0 additions & 3 deletions examples/text_labels_and_annotations/annotation_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,6 @@
xy=(2., -1), xycoords='data',
xytext=(-100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="fancy",
fc="0.6", ec="none",
patchB=el,
Expand All @@ -258,7 +257,6 @@
xy=(2., -1), xycoords='data',
xytext=(100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="simple",
fc="0.6", ec="none",
patchB=el,
Expand All @@ -267,7 +265,6 @@
xy=(2., -1), xycoords='data',
xytext=(-100, -100), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="wedge,tail_width=0.7",
fc="0.6", ec="none",
patchB=el,
Expand Down
1 change: 1 addition & 0 deletions examples/text_labels_and_annotations/arrow_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def make_arrow_graph(ax, data, size=4, display='length', shape='right',
fc=fc, ec=ec or fc, alpha=alpha, width=width,
head_width=head_width, head_length=head_length, shape=shape,
length_includes_head=True,
**kwargs
)

# figure out coordinates for text:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/_docstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def some_function(x):
def __init__(self, *args, **kwargs):
if args and kwargs:
raise TypeError("Only positional or keyword args are allowed")
self.params = params = args or kwargs
self.params = args or kwargs

def __call__(self, func):
if func.__doc__:
Expand Down
8 changes: 1 addition & 7 deletions lib/matplotlib/_layoutgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,13 +507,7 @@ def seq_id():
return '%06d' % next(_layoutboxobjnum)


def print_children(lb):
"""Print the children of the layoutbox."""
for child in lb.children:
print_children(child)


def plot_children(fig, lg=None, level=0, printit=False):
def plot_children(fig, lg=None, level=0):
"""Simple plotting to show where boxes are."""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,7 @@ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,

super().__init__(fps, codec, bitrate, extra_args, metadata)

def setup(self, fig, outfile, dpi, frame_dir=None):
def setup(self, fig, outfile, dpi=None, frame_dir=None):
outfile = Path(outfile)
_api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)

Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/backend_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,24 +284,22 @@ def add_tool(self, name, tool, *args, **kwargs):

# If initially toggled
if tool_obj.toggled:
self._handle_toggle(tool_obj, None, None, None)
self._handle_toggle(tool_obj, None, None)
tool_obj.set_figure(self.figure)

event = ToolEvent('tool_added_event', self, tool_obj)
self._callbacks.process(event.name, event)

return tool_obj

def _handle_toggle(self, tool, sender, canvasevent, data):
def _handle_toggle(self, tool, canvasevent, data):
"""
Toggle tools, need to untoggle prior to using other Toggle tool.
Called from trigger_tool.

Parameters
----------
tool : `.ToolBase`
sender : object
Object that wishes to trigger the tool.
canvasevent : Event
Original Canvas event or None.
data : object
Expand Down Expand Up @@ -360,7 +358,7 @@ def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
sender = self

if isinstance(tool, backend_tools.ToolToggleBase):
self._handle_toggle(tool, sender, canvasevent, data)
self._handle_toggle(tool, canvasevent, data)

tool.trigger(sender, canvasevent, data) # Actually trigger Tool.

Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/backend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ def send_message(self, event):

class RubberbandBase(ToolBase):
"""Draw and remove a rubberband."""
def trigger(self, sender, event, data):
def trigger(self, sender, event, data=None):
"""Call `draw_rubberband` or `remove_rubberband` based on data."""
if not self.figure.canvas.widgetlock.available(sender):
return
Expand Down Expand Up @@ -449,11 +449,11 @@ def trigger(self, sender, event, data=None):
return
super().trigger(sender, event, data)

def enable(self, event):
def enable(self, event=None):
self.set_scale(event.inaxes, 'log')
self.figure.canvas.draw_idle()

def disable(self, event):
def disable(self, event=None):
self.set_scale(event.inaxes, 'linear')
self.figure.canvas.draw_idle()

Expand Down Expand Up @@ -676,7 +676,7 @@ def __init__(self, *args):
self.scrollthresh = .5 # .5 second scroll threshold
self.lastscroll = time.time()-self.scrollthresh

def enable(self, event):
def enable(self, event=None):
"""Connect press/release events and lock the canvas."""
self.figure.canvas.widgetlock(self)
self._idPress = self.figure.canvas.mpl_connect(
Expand All @@ -686,7 +686,7 @@ def enable(self, event):
self._idScroll = self.figure.canvas.mpl_connect(
'scroll_event', self.scroll_zoom)

def disable(self, event):
def disable(self, event=None):
"""Release the canvas and disconnect press/release events."""
self._cancel_action()
self.figure.canvas.widgetlock.release(self)
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,7 @@ def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
med 50th percentile
q1 first quartile (25th percentile)
q3 third quartile (75th percentile)
iqr interquartile range
cilo lower notch around the median
cihi upper notch around the median
whislo end of the lower whisker
Expand Down Expand Up @@ -1239,11 +1240,11 @@ def _compute_conf_interval(data, med, iqr, bootstrap):
stats['med'] = np.nan
stats['q1'] = np.nan
stats['q3'] = np.nan
stats['iqr'] = np.nan
stats['cilo'] = np.nan
stats['cihi'] = np.nan
stats['whislo'] = np.nan
stats['whishi'] = np.nan
stats['med'] = np.nan
continue

# up-convert to an array, just to be safe
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def __init__(self,
def get_paths(self):
return self._paths

def set_paths(self):
def set_paths(self, paths):
raise NotImplementedError

def get_transforms(self):
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/dviread.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,6 @@ def _read(self):
while True:
byte = self.file.read(1)[0]
self._dtable[byte](self, byte)
name = self._dtable[byte].__name__
if byte == 140: # end of page
return True
if self.state is _dvistate.post_post: # end of file
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,7 +890,7 @@ def set_stretch(self, stretch):
return
try:
stretch = int(stretch)
except ValueError as err:
except ValueError:
pass
else:
if 0 <= stretch <= 1000:
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,8 @@ def __init__(self, Q, X, Y, U, label,
self.fontproperties = fontproperties or dict()
self.kw = kwargs
_fp = self.fontproperties
# boxprops = dict(facecolor='red')
self.text = mtext.Text(
text=label, # bbox=boxprops,
text=label,
horizontalalignment=self.halign[self.labelpos],
verticalalignment=self.valign[self.labelpos],
fontproperties=font_manager.FontProperties._from_any(_fp))
Expand Down
7 changes: 1 addition & 6 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3822,8 +3822,6 @@ def test_errorbar_nan(fig_test, fig_ref):
es = np.array([4, 5, np.nan, np.nan, 6])
ax.errorbar(xs, ys, es)
ax = fig_ref.add_subplot()
ys = np.array([1, 2, np.nan, np.nan, 3])
es = np.array([4, 5, np.nan, np.nan, 6])
ax.errorbar([0, 1], [1, 2], [4, 5])
ax.errorbar([4], [3], [6], fmt="C0")

Expand Down Expand Up @@ -7787,10 +7785,7 @@ def test_patch_bounds(): # PR 19078
def test_warn_ignored_scatter_kwargs():
with pytest.warns(UserWarning,
match=r"You passed a edgecolor/edgecolors"):

c = plt.scatter(
[0], [0], marker="+", s=500, facecolor="r", edgecolor="b"
)
plt.scatter([0], [0], marker="+", s=500, facecolor="r", edgecolor="b")


def test_artist_sublists():
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/tests/test_backend_qt.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@

@pytest.fixture
def qt_core(request):
backend, = request.node.get_closest_marker('backend').args
qt_compat = pytest.importorskip('matplotlib.backends.qt_compat')
QtCore = qt_compat.QtCore

Expand Down
Loading