Skip to content

Commit 23ca0e3

Browse files
committed
BUG: Fix Index construction when given empty generator (pandas-dev#21470).
1 parent 576d5c6 commit 23ca0e3

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

pandas/core/indexes/base.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -429,15 +429,18 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None,
429429
elif data is None or is_scalar(data):
430430
cls._scalar_data_error(data)
431431
else:
432-
if tupleize_cols and is_list_like(data) and data:
432+
if tupleize_cols and is_list_like(data):
433+
# GH21470: convert iterable to list before determining if empty
433434
if is_iterator(data):
434435
data = list(data)
435-
# we must be all tuples, otherwise don't construct
436-
# 10697
437-
if all(isinstance(e, tuple) for e in data):
438-
from .multi import MultiIndex
439-
return MultiIndex.from_tuples(
440-
data, names=name or kwargs.get('names'))
436+
437+
if data:
438+
# we must be all tuples, otherwise don't construct
439+
# 10697
440+
if all(isinstance(e, tuple) for e in data):
441+
from .multi import MultiIndex
442+
return MultiIndex.from_tuples(
443+
data, names=name or kwargs.get('names'))
441444
# other iterable of some kind
442445
subarr = com._asarray_tuplesafe(data, dtype=object)
443446
return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs)

pandas/tests/indexes/test_base.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -438,14 +438,22 @@ def test_constructor_dtypes_timedelta(self, attr, klass):
438438
result = klass(list(values), dtype=dtype)
439439
tm.assert_index_equal(result, index)
440440

441-
def test_constructor_empty_gen(self):
441+
def test_constructor_empty_list(self):
442442
skip_index_keys = ["repeats", "periodIndex", "rangeIndex",
443443
"tuples"]
444444
for key, index in self.generate_index_types(skip_index_keys):
445445
empty = index.__class__([])
446446
assert isinstance(empty, index.__class__)
447447
assert not len(empty)
448448

449+
def test_constructor_empty_gen(self):
450+
skip_index_keys = ["repeats", "periodIndex", "rangeIndex",
451+
"tuples"]
452+
for key, index in self.generate_index_types(skip_index_keys):
453+
empty = index.__class__(x for x in [])
454+
assert isinstance(empty, index.__class__)
455+
assert not len(empty)
456+
449457
@pytest.mark.parametrize("empty,klass", [
450458
(PeriodIndex([], freq='B'), PeriodIndex),
451459
(RangeIndex(step=1), pd.RangeIndex),

0 commit comments

Comments
 (0)