Skip to content

Commit

Permalink
Reoder safe_first_element() and _safe_first_finite() code
Browse files Browse the repository at this point in the history
This does not change functionality. The code path for
`safe_first_element` is `_safe_first_finite(skip_nonfinite=False)` which
 is separate code block and does not interact with the
 skip_nonfinite=True case. IMHO this is more readable.
  • Loading branch information
timhoffm committed Sep 18, 2023
1 parent 538bd83 commit 47b1c55
Showing 1 changed file with 15 additions and 19 deletions.
34 changes: 15 additions & 19 deletions lib/matplotlib/cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -1679,10 +1679,20 @@ def safe_first_element(obj):
This is a type-independent way of obtaining the first element,
supporting both index access and the iterator protocol.
"""
return _safe_first_finite(obj, skip_nonfinite=False)
if isinstance(obj, collections.abc.Iterator):
# needed to accept `array.flat` as input.
# np.flatiter reports as an instance of collections.Iterator but can still be
# indexed via []. This has the side effect of re-setting the iterator, but
# that is acceptable.
try:
return obj[0]
except TypeError:
pass
raise RuntimeError("matplotlib does not support generators as input")
return next(iter(obj))


def _safe_first_finite(obj, *, skip_nonfinite=True):
def _safe_first_finite(obj):
"""
Return the first finite element in *obj* if one is available and skip_nonfinite is
True. Otherwise, return the first element.
Expand All @@ -1705,26 +1715,12 @@ def safe_isfinite(val):
# This is something that NumPy cannot make heads or tails of,
# assume "finite"
return True
if skip_nonfinite is False:
if isinstance(obj, collections.abc.Iterator):
# needed to accept `array.flat` as input.
# np.flatiter reports as an instance of collections.Iterator
# but can still be indexed via [].
# This has the side effect of re-setting the iterator, but
# that is acceptable.
try:
return obj[0]
except TypeError:
pass
raise RuntimeError("matplotlib does not support generators "
"as input")
return next(iter(obj))
elif isinstance(obj, np.flatiter):

if isinstance(obj, np.flatiter):
# TODO do the finite filtering on this
return obj[0]
elif isinstance(obj, collections.abc.Iterator):
raise RuntimeError("matplotlib does not "
"support generators as input")
raise RuntimeError("matplotlib does not support generators as input")
else:
for val in obj:
if safe_isfinite(val):
Expand Down

0 comments on commit 47b1c55

Please sign in to comment.