diff -r 7323bced3d48 Lib/ctypes/test/test_numbers.py --- a/Lib/ctypes/test/test_numbers.py Sat Apr 16 18:55:16 2011 +0200 +++ b/Lib/ctypes/test/test_numbers.py Sat Apr 16 18:50:22 2011 -0500 @@ -82,6 +82,16 @@ self.assertRaises(TypeError, t, "") self.assertRaises(TypeError, t, None) + def test_float_overflow(self): + import sys + big_int = int(sys.float_info.max) * 2 + for t in float_types + [c_longdouble]: + self.assertRaises(OverflowError, t, big_int) + if (hasattr(t, "__ctype_be__")): + self.assertRaises(OverflowError, t.__ctype_be__, big_int) + if (hasattr(t, "__ctype_le__")): + self.assertRaises(OverflowError, t.__ctype_le__, big_int) + ## def test_valid_ranges(self): ## # invalid values of the correct type ## # raise ValueError (not OverflowError) diff -r 7323bced3d48 Modules/_ctypes/cfield.c --- a/Modules/_ctypes/cfield.c Sat Apr 16 18:55:16 2011 +0200 +++ b/Modules/_ctypes/cfield.c Sat Apr 16 18:50:22 2011 -0500 @@ -994,6 +994,19 @@ * non-integer accessor methods, not supporting bit fields */ +static void +float_conversion_error(PyObject *value) +{ + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + PyErr_Format(PyExc_OverflowError, + " %s too large to convert to float", + value->ob_type->tp_name); + } else { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + } +} static PyObject * g_set(void *ptr, PyObject *value, Py_ssize_t size) @@ -1002,9 +1015,7 @@ x = PyFloat_AsDouble(value); if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); + float_conversion_error(value); return NULL; } memcpy(ptr, &x, sizeof(long double)); @@ -1026,9 +1037,7 @@ x = PyFloat_AsDouble(value); if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); + float_conversion_error(value); return NULL; } memcpy(ptr, &x, sizeof(double)); @@ -1050,9 +1059,7 @@ x = PyFloat_AsDouble(value); if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); + float_conversion_error(value); return NULL; } #ifdef WORDS_BIGENDIAN @@ -1082,9 +1089,7 @@ x = (float)PyFloat_AsDouble(value); if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); + float_conversion_error(value); return NULL; } memcpy(ptr, &x, sizeof(x)); @@ -1106,9 +1111,7 @@ x = (float)PyFloat_AsDouble(value); if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); + float_conversion_error(value); return NULL; } #ifdef WORDS_BIGENDIAN