Skip to content

Commit 92eb258

Browse files
jbrockmendelroberthdevries
authored andcommitted
CLN: simplify+annotate _shallow_copy (pandas-dev#32244)
1 parent b069c78 commit 92eb258

File tree

7 files changed

+33
-44
lines changed

7 files changed

+33
-44
lines changed

pandas/core/indexes/base.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from pandas._libs import algos as libalgos, index as libindex, lib
1010
import pandas._libs.join as libjoin
11-
from pandas._libs.lib import is_datetime_array
11+
from pandas._libs.lib import is_datetime_array, no_default
1212
from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp
1313
from pandas._libs.tslibs.period import IncompatibleFrequency
1414
from pandas._libs.tslibs.timezones import tz_compare
@@ -485,7 +485,7 @@ def _get_attributes_dict(self):
485485
"""
486486
return {k: getattr(self, k, None) for k in self._attributes}
487487

488-
def _shallow_copy(self, values=None, **kwargs):
488+
def _shallow_copy(self, values=None, name: Label = no_default):
489489
"""
490490
Create a new Index with the same class as the caller, don't copy the
491491
data, use the same object attributes with passed in attributes taking
@@ -496,16 +496,14 @@ def _shallow_copy(self, values=None, **kwargs):
496496
Parameters
497497
----------
498498
values : the values to create the new Index, optional
499-
kwargs : updates the default attributes for this Index
499+
name : Label, defaults to self.name
500500
"""
501+
name = self.name if name is no_default else name
502+
501503
if values is None:
502504
values = self.values
503505

504-
attributes = self._get_attributes_dict()
505-
506-
attributes.update(kwargs)
507-
508-
return self._simple_new(values, **attributes)
506+
return self._simple_new(values, name=name)
509507

510508
def _shallow_copy_with_infer(self, values, **kwargs):
511509
"""

pandas/core/indexes/category.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
from pandas._libs import index as libindex
99
from pandas._libs.hashtable import duplicated_int64
10+
from pandas._libs.lib import no_default
11+
from pandas._typing import Label
1012
from pandas.util._decorators import Appender, cache_readonly
1113

1214
from pandas.core.dtypes.common import (
@@ -264,13 +266,14 @@ def _simple_new(cls, values, name=None, dtype=None):
264266
# --------------------------------------------------------------------
265267

266268
@Appender(Index._shallow_copy.__doc__)
267-
def _shallow_copy(self, values=None, **kwargs):
269+
def _shallow_copy(self, values=None, name: Label = no_default):
270+
name = self.name if name is no_default else name
271+
268272
if values is None:
269273
values = self.values
270274

271275
cat = Categorical(values, dtype=self.dtype)
272276

273-
name = kwargs.get("name", self.name)
274277
return type(self)._simple_new(cat, name=name)
275278

276279
def _is_dtype_compat(self, other) -> bool:

pandas/core/indexes/datetimelike.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from pandas._libs import NaT, iNaT, join as libjoin, lib
1010
from pandas._libs.tslibs import timezones
11+
from pandas._typing import Label
1112
from pandas.compat.numpy import function as nv
1213
from pandas.errors import AbstractMethodError
1314
from pandas.util._decorators import Appender, cache_readonly
@@ -649,26 +650,26 @@ def _set_freq(self, freq):
649650

650651
self._data._freq = freq
651652

652-
def _shallow_copy(self, values=None, **kwargs):
653+
def _shallow_copy(self, values=None, name: Label = lib.no_default):
654+
name = self.name if name is lib.no_default else name
655+
653656
if values is None:
654657
values = self._data
655658

656659
if isinstance(values, type(self)):
657660
values = values._data
658661
if isinstance(values, np.ndarray):
659662
# TODO: We would rather not get here
660-
if kwargs.get("freq") is not None:
661-
raise ValueError(kwargs)
662663
values = type(self._data)(values, dtype=self.dtype)
663664

664665
attributes = self._get_attributes_dict()
665666

666-
if "freq" not in kwargs and self.freq is not None:
667+
if self.freq is not None:
667668
if isinstance(values, (DatetimeArray, TimedeltaArray)):
668669
if values.freq is None:
669670
del attributes["freq"]
670671

671-
attributes.update(kwargs)
672+
attributes["name"] = name
672673
return type(self)._simple_new(values, **attributes)
673674

674675
# --------------------------------------------------------------------
@@ -738,9 +739,7 @@ def intersection(self, other, sort=False):
738739
# this point, depending on the values.
739740

740741
result._set_freq(None)
741-
result = self._shallow_copy(
742-
result._data, name=result.name, dtype=result.dtype, freq=None
743-
)
742+
result = self._shallow_copy(result._data, name=result.name)
744743
if result.freq is None:
745744
result._set_freq("infer")
746745
return result

pandas/core/indexes/numeric.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import numpy as np
44

55
from pandas._libs import index as libindex, lib
6-
from pandas._typing import Dtype
6+
from pandas._typing import Dtype, Label
77
from pandas.util._decorators import Appender, cache_readonly
88

99
from pandas.core.dtypes.cast import astype_nansafe
@@ -103,7 +103,7 @@ def _maybe_cast_slice_bound(self, label, side, kind):
103103
return self._maybe_cast_indexer(label)
104104

105105
@Appender(Index._shallow_copy.__doc__)
106-
def _shallow_copy(self, values=None, name=lib.no_default):
106+
def _shallow_copy(self, values=None, name: Label = lib.no_default):
107107
name = name if name is not lib.no_default else self.name
108108

109109
if values is not None and not self._can_hold_na and values.dtype.kind == "f":

pandas/core/indexes/period.py

+6-13
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
import numpy as np
66

77
from pandas._libs import index as libindex
8+
from pandas._libs.lib import no_default
89
from pandas._libs.tslibs import frequencies as libfrequencies, resolution
910
from pandas._libs.tslibs.parsing import parse_time_string
1011
from pandas._libs.tslibs.period import Period
12+
from pandas._typing import Label
1113
from pandas.util._decorators import Appender, cache_readonly
1214

1315
from pandas.core.dtypes.common import (
@@ -248,8 +250,10 @@ def _has_complex_internals(self):
248250
# used to avoid libreduction code paths, which raise or require conversion
249251
return True
250252

251-
def _shallow_copy(self, values=None, **kwargs):
253+
def _shallow_copy(self, values=None, name: Label = no_default):
252254
# TODO: simplify, figure out type of values
255+
name = name if name is not no_default else self.name
256+
253257
if values is None:
254258
values = self._data
255259

@@ -263,18 +267,7 @@ def _shallow_copy(self, values=None, **kwargs):
263267
# GH#30713 this should never be reached
264268
raise TypeError(type(values), getattr(values, "dtype", None))
265269

266-
# We don't allow changing `freq` in _shallow_copy.
267-
validate_dtype_freq(self.dtype, kwargs.get("freq"))
268-
attributes = self._get_attributes_dict()
269-
270-
attributes.update(kwargs)
271-
if not len(values) and "dtype" not in kwargs:
272-
attributes["dtype"] = self.dtype
273-
return self._simple_new(values, **attributes)
274-
275-
def _shallow_copy_with_infer(self, values=None, **kwargs):
276-
""" we always want to return a PeriodIndex """
277-
return self._shallow_copy(values=values, **kwargs)
270+
return self._simple_new(values, name=name)
278271

279272
def _maybe_convert_timedelta(self, other):
280273
"""

pandas/core/indexes/range.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import numpy as np
88

99
from pandas._libs import index as libindex
10+
from pandas._libs.lib import no_default
11+
from pandas._typing import Label
1012
import pandas.compat as compat
1113
from pandas.compat.numpy import function as nv
1214
from pandas.util._decorators import Appender, cache_readonly
@@ -385,13 +387,13 @@ def tolist(self):
385387
return list(self._range)
386388

387389
@Appender(Int64Index._shallow_copy.__doc__)
388-
def _shallow_copy(self, values=None, **kwargs):
390+
def _shallow_copy(self, values=None, name: Label = no_default):
391+
name = self.name if name is no_default else name
392+
389393
if values is None:
390-
name = kwargs.get("name", self.name)
391394
return self._simple_new(self._range, name=name)
392395
else:
393-
kwargs.setdefault("name", self.name)
394-
return self._int64index._shallow_copy(values, **kwargs)
396+
return Int64Index._simple_new(values, name=name)
395397

396398
@Appender(Int64Index.copy.__doc__)
397399
def copy(self, name=None, deep=False, dtype=None, **kwargs):

pandas/tests/indexes/period/test_period.py

+1-7
Original file line numberDiff line numberDiff line change
@@ -128,15 +128,9 @@ def test_shallow_copy_empty(self):
128128
def test_shallow_copy_i8(self):
129129
# GH-24391
130130
pi = period_range("2018-01-01", periods=3, freq="2D")
131-
result = pi._shallow_copy(pi.asi8, freq=pi.freq)
131+
result = pi._shallow_copy(pi.asi8)
132132
tm.assert_index_equal(result, pi)
133133

134-
def test_shallow_copy_changing_freq_raises(self):
135-
pi = period_range("2018-01-01", periods=3, freq="2D")
136-
msg = "specified freq and dtype are different"
137-
with pytest.raises(IncompatibleFrequency, match=msg):
138-
pi._shallow_copy(pi, freq="H")
139-
140134
def test_view_asi8(self):
141135
idx = PeriodIndex([], freq="M")
142136

0 commit comments

Comments
 (0)