MCPcopy Create free account
hub / github.com/numpy/numpy / PyArray_CanCoerceScalar

Function PyArray_CanCoerceScalar

numpy/core/src/multiarray/multiarraymodule.c:842–895  ·  view source on GitHub ↗

NUMPY_API * * Determines whether the data type 'thistype', with * scalar kind 'scalar', can be coerced into 'neededtype'. */

Source from the content-addressed store, hash-verified

840 * scalar kind 'scalar', can be coerced into 'neededtype'.
841 */
842NPY_NO_EXPORT int
843PyArray_CanCoerceScalar(int thistype, int neededtype,
844 NPY_SCALARKIND scalar)
845{
846 PyArray_Descr* from;
847 int *castlist;
848
849 /* If 'thistype' is not a scalar, it must be safely castable */
850 if (scalar == NPY_NOSCALAR) {
851 return PyArray_CanCastSafely(thistype, neededtype);
852 }
853 if ((unsigned int)neededtype < NPY_NTYPES) {
854 NPY_SCALARKIND neededscalar;
855
856 if (scalar == NPY_OBJECT_SCALAR) {
857 return PyArray_CanCastSafely(thistype, neededtype);
858 }
859
860 /*
861 * The lookup table gives us exactly what we need for
862 * this comparison, which PyArray_ScalarKind would not.
863 *
864 * The rule is that positive scalars can be coerced
865 * to a signed ints, but negative scalars cannot be coerced
866 * to unsigned ints.
867 * _npy_scalar_kinds_table[int]==NEGINT > POSINT,
868 * so 1 is returned, but
869 * _npy_scalar_kinds_table[uint]==POSINT < NEGINT,
870 * so 0 is returned, as required.
871 *
872 */
873 neededscalar = _npy_scalar_kinds_table[neededtype];
874 if (neededscalar >= scalar) {
875 return 1;
876 }
877 if (!PyTypeNum_ISUSERDEF(thistype)) {
878 return 0;
879 }
880 }
881
882 from = PyArray_DescrFromType(thistype);
883 if (from->f->cancastscalarkindto
884 && (castlist = from->f->cancastscalarkindto[scalar])) {
885 while (*castlist != NPY_NOTYPE) {
886 if (*castlist++ == neededtype) {
887 Py_DECREF(from);
888 return 1;
889 }
890 }
891 }
892 Py_DECREF(from);
893
894 return 0;
895}
896
897/* Could perhaps be redone to not make contiguous arrays */
898

Callers

nothing calls this directly

Calls 1

PyArray_CanCastSafelyFunction · 0.85

Tested by

no test coverage detected