Why tuple with one item is no tuple

Kay Schluehr kay.schluehr at gmx.net
Fri Mar 18 09:16:17 CET 2005


Antoon Pardon wrote:

> for instance I have written once somekind of vector class where
> it was natural for these vectors to be added as well as te be
> concatenated. Unfortunately python uses "+" for both so I had
> no way to have both operators in a natural way in python.

Yes this is a quite common problem if one wants to have both an
addition- and a concatenation operator. I created once a <Hex> class
representing both a bytecode  and a number and i resolved the need for
a concatenation by overloading __floordiv__. Both a __div__ and a
__floordiv__ are not needed for most of the types that are not ints.

>>> a,b = Hex(0x78),Hex("00")
>>> a+b
0x78
>>> a//b
0x7800

I would have prefered overloading a common concatenation operaor, say
__cat__ which is mapped onto "||" but i think using "+" for
concatenation comes from the convenience to concatenate strings in this
manner in other languages and has spreaded into the domain of lists and
tuples in Python.

On the other hand i find Mathematicas list operators very appealing:

In =: [1,2,3]^2
Out=: [1,4,9]

Compared with this suggar the list comprehension [x**2 for x in
[1,2,3]]
is ugly.

Regards Kay




More information about the Python-list mailing list