Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Warning if handles and labels have a len mismatch #27004

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
Oct 8, 2023
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
6 changes: 6 additions & 0 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,12 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
_api.warn_external("You have mixed positional and keyword arguments, "
"some input may be discarded.")

if (hasattr(handles, "__len__") and
Copy link
Member

Choose a reason for hiding this comment

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

Is it better do do the hasattr checks or catch (and ignore) the TypeError fro just trying?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wondered the same. My reasoning was that since in the previous discussion it was agreed that only a warning should be raised , it made more sense to check for the attiribute rather than to do a try/except.
From a speed pov, I don't think there is going to be any big differences (try/except should be faster when __ len __ exists and viceversa). This stack discussion could also be useful.

With try/except would be something like:

try:
    if len(handles) != len(labels):
        _api.warn_external(f"Mismatched number of handles and labels: "
                               f"len(handles) = {len(handles)} "
                               f"len(labels) = {len(labels)}")
except TypeError:
    pass

vs the current impl

if (hasattr(handles, "__len__") and
hasattr(labels, "__len__") and
len(handles) != len(labels)):
_api.warn_external(f"Mismatched number of handles and labels: "
f"len(handles) = {len(handles)} "
f"len(labels) = {len(labels)}")

I think using the hasattr() is cleaner, but I don't have a strong opinion about either.

In this file, hasattr is used once before:

# support parasite axes:
if hasattr(ax, 'parasites'):
for axx in ax.parasites:
handles_original += [
*(a for a in axx._children
if isinstance(a, (Line2D, Patch, Collection, Text))),
*axx.containers]

All other cases use try/except.

Copy link
Member

Choose a reason for hiding this comment

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

+0.1 on the version of the PR.
IMHO here: "explicit is better than implicit" > "it's better to ask for foregiveness than for permission", because TypeError is quite generic.

Copy link
Member

Choose a reason for hiding this comment

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

I could see an argument for moving it into the if handles and labels: block, which is already the next check.

That should make it so that both are at least iterable (escaping the one or both is None case), though I guess someone could pass e.g. labels=(str(x) for x in itertools.count()), which has no len and is relying on the zip, so still need some guard against unbounded inputs.

Copy link
Member

@timhoffm timhoffm Oct 5, 2023

Choose a reason for hiding this comment

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

I think this is clearer. We're not obliged to jump extra hoops for user-friendly length checks if the user passes an iterable without a len implementation (which should be quite rare anyway).

hasattr(labels, "__len__") and
len(handles) != len(labels)):
_api.warn_external(f"Mismatched number of handles and labels: "
f"len(handles) = {len(handles)} "
f"len(labels) = {len(labels)}")
# if got both handles and labels as kwargs, make same length
if handles and labels:
handles, labels = zip(*zip(handles, labels))
Expand Down
18 changes: 18 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,3 +1357,21 @@ def test_loc_validation_string_value():
ax.legend(loc='upper center')
with pytest.raises(ValueError, match="'wrong' is not a valid value for"):
ax.legend(loc='wrong')


def test_legend_handle_label_mismatch():
pl1, = plt.plot(range(10))
pl2, = plt.plot(range(10))
with pytest.warns(UserWarning, match="number of handles and labels"):
legend = plt.legend(handles=[pl1, pl2], labels=["pl1", "pl2", "pl3"])
assert len(legend.legend_handles) == 2
assert len(legend.get_texts()) == 2


def test_legend_handle_label_mismatch_no_len():
pl1, = plt.plot(range(10))
pl2, = plt.plot(range(10))
legend = plt.legend(handles=iter([pl1, pl2]),
labels=iter(["pl1", "pl2", "pl3"]))
assert len(legend.legend_handles) == 2
assert len(legend.get_texts()) == 2