Skip to content
Closed
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
22 changes: 8 additions & 14 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1688,22 +1688,16 @@ def safe_first_element(obj):
"""
Return the first element in *obj*.

This is an type-independent way of obtaining the first element, supporting
This is an type-independent way of obtaining the first element(using flatiter from the numpy library), supporting
both index access and the iterator protocol.
"""
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))
if isinstance(obj, np.flatiter):
return obj[0]
elif isinstance(obj, collections.abc.Iterator):
raise RuntimeError("matplotlib does not support generators as input")
else:
#filter out None values
return next(val for val in obj if val is not None)


def sanitize_sequence(data):
Expand Down
12 changes: 12 additions & 0 deletions lib/matplotlib/tests/test_cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,17 @@ def test_safe_first_element_pandas_series(pd):
actual = cbook.safe_first_element(s)
assert actual == 0

def test_safe_first_element_none_value():
#check if None value(s) are skipped over when computing the first element
y = [6, 2, 8, 3, 1, 8, 5, 3, 0, 7]
x = [date.today() + timedelta(days=i) for i in range(10)]
x[0] = None
x[5] = None
x[-1] = None
actual = cbook.safe_first_element(x)
assert actual is not None and actual == x[1]



def test_warn_external(recwarn):
_api.warn_external("oops")
Expand Down Expand Up @@ -888,3 +899,4 @@ def test_format_approx():
assert f(0.0012345600001, 5) == '0.00123'
assert f(-0.0012345600001, 5) == '-0.00123'
assert f(0.0012345600001, 8) == f(0.0012345600001, 10) == '0.00123456'