Skip to content

REF: simplify Index.__new__ #38910

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 2 commits into from
Jan 3, 2021
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
46 changes: 24 additions & 22 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
TYPE_CHECKING,
Any,
Callable,
Dict,
FrozenSet,
Hashable,
List,
Expand Down Expand Up @@ -131,6 +132,11 @@
_Identity = NewType("_Identity", object)


def disallow_kwargs(kwargs: Dict[str, Any]):
if kwargs:
raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}")


def _new_Index(cls, d):
"""
This is called upon unpickling, rather than the default which doesn't
Expand Down Expand Up @@ -296,32 +302,29 @@ def __new__(
return result.astype(dtype, copy=False)
return result

if is_ea_or_datetimelike_dtype(dtype):
elif is_ea_or_datetimelike_dtype(dtype):
# non-EA dtype indexes have special casting logic, so we punt here
klass = cls._dtype_to_subclass(dtype)
if klass is not Index:
return klass(data, dtype=dtype, copy=copy, name=name, **kwargs)

if is_ea_or_datetimelike_dtype(data_dtype):
ea_cls = dtype.construct_array_type()
data = ea_cls._from_sequence(data, dtype=dtype, copy=copy)
data = np.asarray(data, dtype=object)
disallow_kwargs(kwargs)
return Index._simple_new(data, name=name)

elif is_ea_or_datetimelike_dtype(data_dtype):
klass = cls._dtype_to_subclass(data_dtype)
if klass is not Index:
result = klass(data, copy=copy, name=name, **kwargs)
if dtype is not None:
return result.astype(dtype, copy=False)
return result

# extension dtype
if is_extension_array_dtype(data_dtype) or is_extension_array_dtype(dtype):
if not (dtype is None or is_object_dtype(dtype)):
# coerce to the provided dtype
ea_cls = dtype.construct_array_type()
data = ea_cls._from_sequence(data, dtype=dtype, copy=False)
else:
data = np.asarray(data, dtype=object)

# coerce to the object dtype
data = data.astype(object)
return Index(data, dtype=object, copy=copy, name=name, **kwargs)
data = np.array(data, dtype=object, copy=copy)
disallow_kwargs(kwargs)
return Index._simple_new(data, name=name)

# index-like
elif isinstance(data, (np.ndarray, Index, ABCSeries)):
Expand All @@ -333,7 +336,7 @@ def __new__(
# should not be coerced
# GH 11836
data = _maybe_cast_with_dtype(data, dtype, copy)
dtype = data.dtype # TODO: maybe not for object?
dtype = data.dtype

if data.dtype.kind in ["i", "u", "f"]:
# maybe coerce to a sub-class
Expand All @@ -342,16 +345,15 @@ def __new__(
arr = com.asarray_tuplesafe(data, dtype=object)

if dtype is None:
new_data = _maybe_cast_data_without_dtype(arr)
new_dtype = new_data.dtype
return cls(
new_data, dtype=new_dtype, copy=copy, name=name, **kwargs
)
arr = _maybe_cast_data_without_dtype(arr)
dtype = arr.dtype

if kwargs:
return cls(arr, dtype, copy=copy, name=name, **kwargs)

klass = cls._dtype_to_subclass(arr.dtype)
arr = klass._ensure_array(arr, dtype, copy)
if kwargs:
raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}")
disallow_kwargs(kwargs)
return klass._simple_new(arr, name)

elif is_scalar(data):
Expand Down
8 changes: 2 additions & 6 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ def _convert_arr_indexer(self, keyarr):
return com.asarray_tuplesafe(keyarr)


class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin):
"""
Mixin class for methods shared by DatetimeIndex and TimedeltaIndex,
but not PeriodIndex
Expand Down Expand Up @@ -816,11 +816,7 @@ def _union(self, other, sort):
i8self = Int64Index._simple_new(self.asi8)
i8other = Int64Index._simple_new(other.asi8)
i8result = i8self._union(i8other, sort=sort)
# pandas\core\indexes\datetimelike.py:887: error: Unexpected
# keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg]
result = type(self)(
i8result, dtype=self.dtype, freq="infer" # type: ignore[call-arg]
)
result = type(self)(i8result, dtype=self.dtype, freq="infer")
return result

# --------------------------------------------------------------------
Expand Down