Search code examples
pythonconcatenation

Why does Python not have implicit conversions?


Unlike in C++ or Java, whenever I have something like print "Hello " + 1, I get an error that it can't concatenate str and int objects. Why isn't this conversion done implicitly in Python?


Solution

  • print "Hello", 1
    

    The reason concatenation doesn't work is that string objects don't have any code in them to perform type conversion as part of their __add__() method. As for why, presumably Guido thought it would be a bad idea. The Zen of Python says "explicit is better than implicit."

    You could write a string subclass that works this way, however:

    class MagicStr(str):
        def __add__(self, other):
            return MagicStr(str(self) + str(other))
        def __radd__(self, other):
            return MagicStr(str(other) + str(self))
        __iadd__ = __add__
    

    Of course, there's no way to get Python to use that class for string literals or for user input, so you end up having to convert strings constantly:

     MagicStr("Hello") + 1
    

    At which point you might as well just write:

     "Hello" + str(1)