Skip to content

Commit c5da5ea

Browse files
Backport PR #55707 on branch 2.1.x (REF: Avoid np.can_cast for scalar inference for NEP 50) (#55716)
Backport PR #55707: REF: Avoid np.can_cast for scalar inference for NEP 50 Co-authored-by: Matthew Roeschke <[email protected]>
1 parent d11fa8d commit c5da5ea

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

ci/run_tests.sh

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ echo PYTHONHASHSEED=$PYTHONHASHSEED
1010

1111
COVERAGE="-s --cov=pandas --cov-report=xml --cov-append --cov-config=pyproject.toml"
1212

13-
PYTEST_CMD="MESONPY_EDITABLE_VERBOSE=1 PYTHONDEVMODE=1 PYTHONWARNDEFAULTENCODING=1 pytest -r fEs -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET"
13+
# TODO: Support NEP 50 and remove NPY_PROMOTION_STATE
14+
PYTEST_CMD="NPY_PROMOTION_STATE=legacy MESONPY_EDITABLE_VERBOSE=1 PYTHONDEVMODE=1 PYTHONWARNDEFAULTENCODING=1 pytest -r fEs -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET"
1415

1516
if [[ "$PATTERN" ]]; then
1617
PYTEST_CMD="$PYTEST_CMD -m \"$PATTERN\""

pandas/core/dtypes/cast.py

+23-2
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
700700
dtype = np.dtype(np.object_)
701701

702702
elif issubclass(dtype.type, np.integer):
703-
if not np.can_cast(fill_value, dtype):
703+
if not np_can_cast_scalar(fill_value, dtype): # type: ignore[arg-type]
704704
# upcast to prevent overflow
705705
mst = np.min_scalar_type(fill_value)
706706
dtype = np.promote_types(dtype, mst)
@@ -1892,4 +1892,25 @@ def _dtype_can_hold_range(rng: range, dtype: np.dtype) -> bool:
18921892
"""
18931893
if not len(rng):
18941894
return True
1895-
return np.can_cast(rng[0], dtype) and np.can_cast(rng[-1], dtype)
1895+
return np_can_cast_scalar(rng.start, dtype) and np_can_cast_scalar(rng.stop, dtype)
1896+
1897+
1898+
def np_can_cast_scalar(element: Scalar, dtype: np.dtype) -> bool:
1899+
"""
1900+
np.can_cast pandas-equivalent for pre 2-0 behavior that allowed scalar
1901+
inference
1902+
1903+
Parameters
1904+
----------
1905+
element : Scalar
1906+
dtype : np.dtype
1907+
1908+
Returns
1909+
-------
1910+
bool
1911+
"""
1912+
try:
1913+
np_can_hold_element(dtype, element)
1914+
return True
1915+
except (LossySetitemError, NotImplementedError):
1916+
return False

0 commit comments

Comments
 (0)