[pypy-commit] pypy default: Give better error messages for '%d' % 'not an int' (and %x, %o).

devin.jeanpierre pypy.commits at gmail.com
Tue May 3 19:20:21 EDT 2016


Author: Devin Jeanpierre <jeanpierreda at gmail.com>
Branch: 
Changeset: r84181:75c1b672983d
Date: 2016-05-03 16:19 -0700
http://bitbucket.org/pypy/pypy/changeset/75c1b672983d/

Log:	Give better error messages for '%d' % 'not an int' (and %x, %o).

	Before: TypeError: unsupported operand type for long(): 'str' After:
	TypeError: %d format: a number is required, not str (same as
	CPython).

diff --git a/pypy/objspace/std/formatting.py b/pypy/objspace/std/formatting.py
--- a/pypy/objspace/std/formatting.py
+++ b/pypy/objspace/std/formatting.py
@@ -551,7 +551,15 @@
         try:
             w_value = maybe_int(space, w_value)
         except OperationError:
-            w_value = space.long(w_value)
+            try:
+                w_value = space.long(w_value)
+            except OperationError as operr:
+                if operr.match(space, space.w_TypeError):
+                    raise oefmt(
+                        space.w_TypeError,
+                        "%s format: a number is required, not %T", fmt, w_value)
+                else:
+                    raise
         try:
             value = space.int_w(w_value)
             return fmt % (value,)
diff --git a/pypy/objspace/std/test/test_bytesobject.py b/pypy/objspace/std/test/test_bytesobject.py
--- a/pypy/objspace/std/test/test_bytesobject.py
+++ b/pypy/objspace/std/test/test_bytesobject.py
@@ -103,6 +103,12 @@
             assert result == "a foo b"
             assert isinstance(result, cls)
 
+    def test_format_wrongtype(self):
+        for int_format in '%d', '%o', '%x':
+            exc_info = raises(TypeError, int_format.__mod__, '123')
+            expected = int_format + ' format: a number is required, not str'
+            assert str(exc_info.value) == expected
+
     def test_split(self):
         assert "".split() == []
         assert "".split('x') == ['']


More information about the pypy-commit mailing list