Skip to content

Commit ff5cae7

Browse files
authored
REF: Avoid np.can_cast for scalar inference for NEP 50 (#55707)
* REF: Avoid np.can_cast for scalar inference for NEP 50 * Use helper function * end->stop * ignore typing * Address NEP 50 later
1 parent 0cbe41a commit ff5cae7

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
@@ -699,7 +699,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
699699
dtype = np.dtype(np.object_)
700700

701701
elif issubclass(dtype.type, np.integer):
702-
if not np.can_cast(fill_value, dtype):
702+
if not np_can_cast_scalar(fill_value, dtype): # type: ignore[arg-type]
703703
# upcast to prevent overflow
704704
mst = np.min_scalar_type(fill_value)
705705
dtype = np.promote_types(dtype, mst)
@@ -1916,4 +1916,25 @@ def _dtype_can_hold_range(rng: range, dtype: np.dtype) -> bool:
19161916
"""
19171917
if not len(rng):
19181918
return True
1919-
return np.can_cast(rng[0], dtype) and np.can_cast(rng[-1], dtype)
1919+
return np_can_cast_scalar(rng.start, dtype) and np_can_cast_scalar(rng.stop, dtype)
1920+
1921+
1922+
def np_can_cast_scalar(element: Scalar, dtype: np.dtype) -> bool:
1923+
"""
1924+
np.can_cast pandas-equivalent for pre 2-0 behavior that allowed scalar
1925+
inference
1926+
1927+
Parameters
1928+
----------
1929+
element : Scalar
1930+
dtype : np.dtype
1931+
1932+
Returns
1933+
-------
1934+
bool
1935+
"""
1936+
try:
1937+
np_can_hold_element(dtype, element)
1938+
return True
1939+
except (LossySetitemError, NotImplementedError):
1940+
return False

0 commit comments

Comments
 (0)