[Python-ideas] String interpolation again.

Masklinn masklinn at masklinn.net
Fri Jul 23 15:50:26 CEST 2010

On 2010-07-23, at 15:37 , Mike Meyer wrote:
> On Fri, 23 Jul 2010 15:25:42 +0200
> Masklinn <masklinn at masklinn.net> wrote:
>> On 2010-07-23, at 15:05 , Mike Meyer wrote:
>>> The first problem with this kind of thing is that there's no obvious
>>> reason why 12 + '34' should be '1234' instead of 46.
>>> Java variables have declared types. This means the above situation can
>>> be detected at compile time, and the implicit conversion added
>>> then. In Python, you have to do the tests at run time, which will slow
>>> everything down.
>> Actually, it's much simpler than that for Java: the `+` operator is specially overloaded any time a string is involved to become a "convert and concatenate" operator similar to PHP's "." rather than the usual "add" operator.
>> In Python, the equivalent behavior would be to special case the addition operator so that it checks if either operand is a string and if it is convert and concatenate the other one, otherwise apply normal resolution.
> I would hope the Java version isn't as convoluted as you say (but
> given Java, it may be): all this really requires is that the string
> version of + include the conversion.
There isn't really such a thing as "the string version of +" as Java forbids userland operator overloading. String's + is a special case in the language as it is, indeed, one of the very few (if not the only) overloaded operator.

To understand how far this goes, Java's BigInteger (their equivalent to Python's long) doesn't have *any* operator overloading. If a is a BigInteger and b is a BigInteger, you add them by writing `a.add(b)`. Likewise for substraction, multiplication, division, negation or bit-twiddling[0]

And if either is *not* a BigInteger, then you convert it to a BigInteger first. If it's a primitive integer type, you cannot even use a constructor, you have to use `BigInteger.valueOf(long)`

> In python, that would be making
> str.__add__ (and friends) do the conversion.
You'd run into the issues of writing `a + "foo"` with `a` defining a custom `__add__`, which would not perform string concatenation, as per Python's operator resolution order.

[0] http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/math/BigInteger.html

More information about the Python-ideas mailing list