Skip to content

REF: avoid circular (runtime) import in dtypes.cast #40155

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
Mar 1, 2021
Merged
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
15 changes: 9 additions & 6 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
iNaT,
ints_to_pydatetime,
)
from pandas._libs.tslibs.timedeltas import array_to_timedelta64
from pandas._typing import (
AnyArrayLike,
ArrayLike,
Expand Down Expand Up @@ -1459,14 +1460,15 @@ def try_timedelta(v: np.ndarray) -> np.ndarray:
# safe coerce to timedelta64

# will try first with a string & object conversion
from pandas import to_timedelta

try:
td_values = to_timedelta(v)
# bc we know v.dtype == object, this is equivalent to
# `np.asarray(to_timedelta(v))`, but using a lower-level API that
# does not require a circular import.
td_values = array_to_timedelta64(v).view("m8[ns]")
except (ValueError, OverflowError):
return v.reshape(shape)
else:
return np.asarray(td_values).reshape(shape)
return td_values.reshape(shape)

inferred_type = lib.infer_datetimelike_array(ensure_object(v))

Expand Down Expand Up @@ -1500,8 +1502,8 @@ def maybe_cast_to_datetime(
try to cast the array/value to a datetimelike dtype, converting float
nan to iNaT
"""
from pandas.core.arrays.timedeltas import sequence_to_td64ns
from pandas.core.tools.datetimes import to_datetime
from pandas.core.tools.timedeltas import to_timedelta

if not is_list_like(value):
raise TypeError("value must be listlike")
Expand Down Expand Up @@ -1582,7 +1584,8 @@ def maybe_cast_to_datetime(
# so localize and convert
value = dta.tz_localize("UTC").tz_convert(dtype.tz)
elif is_timedelta64:
value = to_timedelta(value, errors="raise")._values
# if successful, we get a ndarray[td64ns]
value, _ = sequence_to_td64ns(value)
except OutOfBoundsDatetime:
raise
except ValueError as err:
Expand Down