f---ing typechecking

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Feb 14 23:52:03 EST 2007


On Wed, 14 Feb 2007 19:45:14 -0800, James Stroud wrote:

> Steven D'Aprano wrote:
>> On Wed, 14 Feb 2007 13:25:21 -0800, James Stroud wrote:
>> 
>> 
>>>But then again, the unimaginative defense would be that it wouldn't be 
>>>python if you could catentate a list and a tuple.
>> 
>> 
>> Since lists and tuples are completely different objects with completely
>> different usages, what should concatenating a list and a tuple give?
>> Should it depend on the order you pass them?
> 
> Is that a guess or just common sense?

Sorry, is *what* a guess?

Conceptually, ints are a subset of floats (they certainly are in pure
mathematics). Automatic coercions from ints to floats makes sense;
automatic coercions the other way rarely do -- should you round up or
round down or truncate? What is right in one application is not right for
another.

Lists and tuples, on the other hand, are conceptually two distinct data
types. Adding a list to a tuple is no more sensible than adding a list to
a string -- just because they're both sequences doesn't mean adding them
together is meaningful.


>> 1.0 + 1 == 1 + 1.0 for very good reasons: we consider (for pragmatic
>> reasons to do with loss of significant digits) that floats coerce ints
>> into floats rather than the other way around. But what should lists and
>> tuples do?
>> 
>> From the Zen of Python:
>> "In the face of ambiguity, refuse the temptation to guess."
> 
> Do you guess with __add__ and __radd__?

No. If there is an obviously correct behaviour for addition (like with
ints and floats) then I coerce the objects appropriately. If there is no
obviously correct behaviour, I refuse to guess.

The user's expected behaviour for [1] + (1,) might be to return a list, or
it might be to return a tuple. Since there is no obviously correct
behaviour, the right thing to do is to refuse to guess.


-- 
Steven D'Aprano 




More information about the Python-list mailing list