Skip to content

Commit 12e78f4

Browse files
authored
REF: simplify _try_cast (#41705)
1 parent 9004414 commit 12e78f4

File tree

2 files changed

+11
-22
lines changed

2 files changed

+11
-22
lines changed

pandas/core/construction.py

+8-20
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@
1717
import numpy.ma as ma
1818

1919
from pandas._libs import lib
20-
from pandas._libs.tslibs import (
21-
IncompatibleFrequency,
22-
OutOfBoundsDatetime,
23-
)
20+
from pandas._libs.tslibs import IncompatibleFrequency
2421
from pandas._typing import (
2522
AnyArrayLike,
2623
ArrayLike,
@@ -719,9 +716,7 @@ def _try_cast(
719716
# while maybe_cast_to_datetime treats it as UTC
720717
# see test_maybe_promote_any_numpy_dtype_with_datetimetz
721718

722-
# error: Incompatible return value type (got "Union[ExtensionArray,
723-
# ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]")
724-
return maybe_cast_to_datetime(arr, dtype) # type: ignore[return-value]
719+
return maybe_cast_to_datetime(arr, dtype)
725720
# TODO: copy?
726721

727722
array_type = dtype.construct_array_type()._from_sequence
@@ -734,6 +729,9 @@ def _try_cast(
734729
return subarr
735730
return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy)
736731

732+
elif dtype.kind in ["m", "M"]:
733+
return maybe_cast_to_datetime(arr, dtype)
734+
737735
try:
738736
# GH#15832: Check if we are requesting a numeric dtype and
739737
# that we can convert the data to the requested dtype.
@@ -743,26 +741,16 @@ def _try_cast(
743741
maybe_cast_to_integer_array(arr, dtype)
744742
subarr = arr
745743
else:
746-
subarr = maybe_cast_to_datetime(arr, dtype)
747-
if dtype is not None and dtype.kind == "M":
748-
return subarr
744+
subarr = arr
749745

750746
if not isinstance(subarr, ABCExtensionArray):
751747
# 4 tests fail if we move this to a try/except/else; see
752748
# test_constructor_compound_dtypes, test_constructor_cast_failure
753749
# test_constructor_dict_cast2, test_loc_setitem_dtype
754750
subarr = construct_1d_ndarray_preserving_na(subarr, dtype, copy=copy)
755751

756-
except OutOfBoundsDatetime:
757-
# in case of out of bound datetime64 -> always raise
758-
raise
759-
except (ValueError, TypeError) as err:
760-
if dtype is not None and raise_cast_failure:
761-
raise
762-
elif "Cannot cast" in str(err) or "cannot be converted to timedelta64" in str(
763-
err
764-
):
765-
# via _disallow_mismatched_datetimelike
752+
except (ValueError, TypeError):
753+
if raise_cast_failure:
766754
raise
767755
else:
768756
subarr = np.array(arr, dtype=object, copy=copy)

pandas/core/dtypes/cast.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1579,7 +1579,7 @@ def try_timedelta(v: np.ndarray) -> np.ndarray:
15791579

15801580
def maybe_cast_to_datetime(
15811581
value: ExtensionArray | np.ndarray | list, dtype: DtypeObj | None
1582-
) -> ExtensionArray | np.ndarray | list:
1582+
) -> ExtensionArray | np.ndarray:
15831583
"""
15841584
try to cast the array/value to a datetimelike dtype, converting float
15851585
nan to iNaT
@@ -1705,7 +1705,8 @@ def maybe_cast_to_datetime(
17051705
"maybe_cast_to_datetime allows a list *only* if dtype is not None"
17061706
)
17071707

1708-
return value
1708+
# at this point we have converted or raised in all cases where we had a list
1709+
return cast(ArrayLike, value)
17091710

17101711

17111712
def sanitize_to_nanoseconds(values: np.ndarray, copy: bool = False) -> np.ndarray:

0 commit comments

Comments
 (0)