Skip to content

REF: be stricter about what we pass to _simple_new #31055

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 3 commits into from
Jan 18, 2020
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
3 changes: 2 additions & 1 deletion pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ def __init__(self, values, freq=None, dtype=None, copy=False):
self._dtype = PeriodDtype(freq)

@classmethod
def _simple_new(cls, values, freq=None, **kwargs):
def _simple_new(cls, values: np.ndarray, freq=None, **kwargs):
# alias for PeriodArray.__init__
assert isinstance(values, np.ndarray) and values.dtype == "i8"
return cls(values, freq=freq, **kwargs)

@classmethod
Expand Down
12 changes: 2 additions & 10 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
from pandas.core.dtypes.generic import (
ABCCategorical,
ABCDataFrame,
ABCDatetimeArray,
ABCDatetimeIndex,
ABCIndexClass,
ABCIntervalIndex,
Expand Down Expand Up @@ -459,11 +458,7 @@ def _simple_new(cls, values, name=None, dtype=None):

Must be careful not to recurse.
"""
if isinstance(values, (ABCSeries, ABCIndexClass)):
# Index._data must always be an ndarray.
# This is no-copy for when _values is an ndarray,
# which should be always at this point.
values = np.asarray(values._values)
assert isinstance(values, np.ndarray), type(values)

result = object.__new__(cls)
result._data = values
Expand Down Expand Up @@ -509,17 +504,14 @@ def _get_attributes_dict(self):
def _shallow_copy(self, values=None, **kwargs):
if values is None:
values = self.values

attributes = self._get_attributes_dict()
attributes.update(kwargs)
if not len(values) and "dtype" not in kwargs:
attributes["dtype"] = self.dtype

# _simple_new expects an the type of self._data
values = getattr(values, "_values", values)
if isinstance(values, ABCDatetimeArray):
# `self.values` returns `self` for tz-aware, so we need to unwrap
# more specifically
values = values.asi8

return self._simple_new(values, **attributes)

Expand Down
4 changes: 0 additions & 4 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,6 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=None):
freq = values.freq
values = values._data

# DatetimeArray._simple_new will accept either i8 or M8[ns] dtypes
if isinstance(values, DatetimeIndex):
values = values._data

dtype = tz_to_dtype(tz)
dtarr = DatetimeArray._simple_new(values, freq=freq, dtype=dtype)
assert isinstance(dtarr, DatetimeArray)
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ def _simple_new(cls, array, name, closed=None):
closed : Any
Ignored.
"""
assert isinstance(array, IntervalArray), type(array)

result = IntervalMixin.__new__(cls)
result._data = array
result.name = name
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class NumericIndex(Index):

def __new__(cls, data=None, dtype=None, copy=False, name=None):
cls._validate_dtype(dtype)
name = maybe_extract_name(name, data, cls)

# Coerce to ndarray if not already ndarray or Index
if not isinstance(data, (np.ndarray, Index)):
Expand All @@ -77,7 +78,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None):
# GH#13601, GH#20285, GH#27125
raise ValueError("Index data must be 1-dimensional")

name = maybe_extract_name(name, data, cls)
subarr = np.asarray(subarr)
return cls._simple_new(subarr, name=name)

@classmethod
Expand Down
2 changes: 0 additions & 2 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,6 @@ def _simple_new(cls, values, name=None, freq=None, **kwargs):
freq = Period._maybe_convert_freq(freq)
values = PeriodArray(values, freq=freq)

if not isinstance(values, PeriodArray):
raise TypeError("PeriodIndex._simple_new only accepts PeriodArray")
result = object.__new__(cls)
result._data = values
# For groupby perf. See note in indexes/base about _index_data
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def __new__(
return cls._simple_new(rng, dtype=dtype, name=name)

@classmethod
def from_range(cls, data, name=None, dtype=None):
def from_range(cls, data: range, name=None, dtype=None) -> "RangeIndex":
"""
Create RangeIndex from a range object.

Expand Down
8 changes: 5 additions & 3 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,13 @@ def __new__(
tdarr = TimedeltaArray._from_sequence(
data, freq=freq, unit=unit, dtype=dtype, copy=copy
)
return cls._simple_new(tdarr._data, freq=tdarr.freq, name=name)
return cls._simple_new(tdarr, name=name)

@classmethod
def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE):
# `dtype` is passed by _shallow_copy in corner cases, should always
# be timedelta64[ns] if present

if not isinstance(values, TimedeltaArray):
values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq)
else:
Expand Down Expand Up @@ -420,7 +421,8 @@ def insert(self, loc, item):
new_i8s = np.concatenate(
(self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)
)
return self._shallow_copy(new_i8s, freq=freq)
tda = type(self._data)._simple_new(new_i8s, freq=freq)
Copy link
Contributor

Choose a reason for hiding this comment

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

doen't this copy twice?

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, simple_new doesnt make a copy

Copy link
Contributor

Choose a reason for hiding this comment

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

k, that's what i thought, can you (followup ok), document this loudly in the _simple_new

return self._shallow_copy(tda)
except (AttributeError, TypeError):

# fall back to object index
Expand Down Expand Up @@ -507,4 +509,4 @@ def timedelta_range(

freq, freq_infer = dtl.maybe_infer_freq(freq)
tdarr = TimedeltaArray._generate_range(start, end, periods, freq, closed=closed)
return TimedeltaIndex._simple_new(tdarr._data, freq=tdarr.freq, name=name)
return TimedeltaIndex._simple_new(tdarr, name=name)