Skip to content

Conversation

@zacharym-collins
Copy link
Contributor

@zacharym-collins zacharym-collins commented Dec 17, 2025

Description:
This PR aligns the behavior of DatetimeIndex, TimedeltaIndex, PeriodIndex, and IntervalIndex with the base Index class (and Series) regarding the copy parameter.

Before, these constructors would ignore copy=None and default to not copying the input data.
Now, copy=None defaults to True for np.ndarray and ExtensionArray inputs, ensuring that the resulting Index does not share memory with the mutable input array by default.

Changes:

  • Updated __new__ signatures in datetimes.py, timedeltas.py, period.py, and interval.py to accept copy: bool | None.
  • Added logic to trigger a copy if copy is None (or True) and the input is an array/EA.
  • Updated docstrings to match the standard Index docstring for the copy parameter.
  • Added regression tests for all 4 subclasses verifying that inputs are copied by default and that read-only inputs are handled correctly.
  • Improved robustness by ensuring string dtype arguments (e.g. "datetime64[ns]") are converted to DtypeObj before the view checks, preventing AttributeError.
  • I Updated existing regression tests (test_constructor_int64_nocopy and test_array_tz) to explicitly pass copy=False. Since the default behavior changed to copy=True, these tests required an update to continue verifying that the view based construction is still possible when requested.

@zacharym-collins
Copy link
Contributor Author

All checks are passing now. I've updated the PR to reflect the latest changes.

Comment on lines 692 to 700
if isinstance(data, (ExtensionArray, np.ndarray)):
# GH 63388
if copy is not False:
if dtype is None or astype_is_view(
data.dtype,
pandas_dtype(dtype),
):
data = data.copy()
copy = False
Copy link
Member

Choose a reason for hiding this comment

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

Can you create a @classmethod (place it in indexes/base.py near _raise_scalar_data_error), that encapsulates this logic and can be called here instead?

@mroeschke mroeschke added API Design Index Related to the Index class or subclasses labels Dec 17, 2025
Extracts the copy/view validation logic into a shared classmethod on the base Index class, as requested during review.
Updates DatetimeIndex, TimedeltaIndex, PeriodIndex, and IntervalIndex to use the shared validation logic, reducing code duplication.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

API Design Index Related to the Index class or subclasses

Projects

None yet

Development

Successfully merging this pull request may close these issues.

API: copy np.ndarray inputs to Index subclass constructors by default

2 participants