[Python-Dev] Banishing apply(), buffer(), coerce(), and intern()
Guido van Rossum
guido at python.org
Sun Nov 30 20:08:14 EST 2003
> I don't know if it should be *that* mechanical; there are a lot of
> places where I've seen " 'something %s' % repr(foo)" when I think
> it's much more clearly written as " 'something %r' % foo". I don't
> know which is the officially preferred style, but if it's the latter
> (and I hope it is ;)) then it may not be good to mechanically change
> backticks to a repr call.
If you're going to do that, I would beware of one thing. If x is a
tuple, "foo %r" % x will not do the right thing: it will expect x to
be a 1-tuple and produce the repr of x[0]:
>>> a = (42,)
>>> print "foo %s" % repr(a)
foo (42,)
>>> print "foo %r" % a
foo 42
>>> a = (4, 2)
>>> print "foo %r" % a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: not all arguments converted during string formatting
>>>
This is only a problem when there's only one % format in the string;
if there are two or more, the argument is already a tuple and the
substitution of %s/repr(x) to %r/x works fine. This also suggests a
solution: if there's only one argument, create an explicit tuple:
>>> print "foo %r" % (a,)
foo (4, 2)
>>>
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list