f---ing typechecking

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Feb 15 01:48:10 EST 2007


On Wed, 14 Feb 2007 22:21:43 -0800, James Stroud wrote:

>> 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.
> 
> I guess we differ on what is obvious. This seems obvious to me:
> 
> [1] + (1,) => [1, 1]
> (1,) + [1] => (1, 1)
> 
> simply becuase the operand on the left should take precendence because 
> its "__add__" is called and its "__add__" returns a list.

But that's data dependent. When you call 

[1] + MyTuple(1)

your MyTuple.__radd__ will be called first, not the list's __add__.



> In essence, as 
> we know the obviously correct behavior for __add__ and __radd__, then it 
> would be the obviously correct behavior that the above would follow.

But we don't know the obviously correct behaviour. Why should list.__add__
return a list if the other operand is a tuple? You're assuming what I'm
asking you to justify.

int.__add__ doesn't necessarily return an int. Why should lists
be different?


> I would venture to guess that most people would intuitively consider the 
> above behavior correct, 

I dare say you are right for *some* people. After all, Perl and other
weakly-typed languages try to coerce virtually all types. I doubt it is
a majority. 


> simply because the information content 
> difference between a list versus a tuple is non-existent (outside of the 
> information that one is a list and the other a tuple). Why would their 
> types dictate coercion? 

But that's what you're doing -- implicit coercion.

[1] + (1,) == [1] + [1]
(1,) + [1] == (1,) + (1,)

I don't believe there is any justification for doing such coercion for
lists and tuples.


> With ints and floats, as you point out, the 
> reasons that type dictates coercion are obvious and mathematical. Thus, 
> for tuples and lists, it wouldn't make sense to consider one type taking 
> precendence over the other, so we fall back to position, which seems to 
> be the common sense approach.

I would say the commonsense approach is to refuse the temptation to guess
in the face of ambiguity. Since neither coercing lists to tuples nor
tuples to lists is more obviously correct, raising an exception is the
sensible behaviour. Let the caller choose the correct coercion to use.



-- 
Steven D'Aprano 




More information about the Python-list mailing list