Python was designed (was Re: Multi-threading in Python vs Java)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Oct 15 11:01:58 EDT 2013


On Tue, 15 Oct 2013 19:57:50 +1100, Chris Angelico wrote:

> On Tue, Oct 15, 2013 at 6:48 PM, Antoon Pardon
> <antoon.pardon at rece.vub.ac.be> wrote:

>> That doesn't matter. Adding and concating are different operations and
>> their are types in which both occur rather naturally. So as a designer
>> of such a class you have to choose for which operation you use the
>> natural python operator and for which operation you have to do it
>> differently. NumPy is just an example that you can't escape this sort
>> of incompatibilities in python.
> 
> So what should "abc" + "def" result in, if addition is different from
> concatenation? 

TypeError, like any other unsupported operator.


> No, adding strings should concatenate them. And other
> arithmetic operators make sense, too; 

For some definition of "sense".


> Python doesn't happen to implement str-str or str/str, but some
> languages do:

Which languages are you talking about?

For the record, if PHP is one of them, I consider that a good sign that 
it shouldn't be done :-)


>> "abc"+"def"-"abc";
> (1) Result: "def"

Eww. What would "xyz" - "abc" give? How about "cba" - "abc"?

And "abcdabc" - "abc"?

Justify your answers.



>> "abc"-"b";
> (2) Result: "ac"
>> "foo bar asdf qwer"/" "*"##";
> (3) Result: "foo##bar##asdf##qwer"

And what, pray tell, would "foo bar" / " " be on its own?

How about "foo bar" * "*"?

Seems to me that using s/t*u as a way to perform substring replacement is 
too clever by half.


> PHP has separate addition and concatenation operators, and it doesn't
> help anything

That's because PHP is beyond help.


> (granted, the biggest problem is that every other language
> we work with uses + to concat strings, so it's an easy source of bugs);
> having multiple operators for "add the elements of these arrays" and
> "add these arrays together" is really orthogonal to the general issue of
> adding and concatenating needing different operators.

Yes -- string concatenation and array operations are not really related, 
although string concatenation is a special case of array concatenation. 
But it is a wild over-generalisation to assume that because strings are 
arrays, and (numeric) arrays might want separate element-wise 
multiplication and whole-array multiplication operators, therefore 
strings need to support the same too.

Personally, I think string and array concatenation ought to be & rather 
than +. That would free up + for element-wise addition for arrays, while 
still allowing & for concatenation. Of course, the cost would be the loss 
of an element-wise bit-and operator. You win some, you lose some.



-- 
Steven



More information about the Python-list mailing list