'20' <= 100

Dave Brueck dave at pythonapocrypha.com
Thu May 1 20:34:07 EDT 2003


On Fri, 2 May 2003, [ISO-8859-1] Gerhard Häring wrote:

> Dave Brueck wrote:
> > [...] Put another way, if you give Python:
> >
> > s = '20'
> > t = 2
> > x = s * t
> >
> > How can it know that you expected 40 instead of '2020'?
>
> Sure, but if you give Pyhthon:
>
> s = '20'
> t = 2
> if s < 6:
> 	...
>
> like the OP did, Python should tempt the tempation to guess, like it
> usually does. The comparison operators should IMO be changed to raise a
> TypeError in this case.

But Python didn't really guess at anything - a guess would be implicitly
call int on the string or something. This is a well-documented "feature"
and really only causes problems when there is a bug _elsewhere_ in your
program.

> strings should only be comparable to other basestrings and numbers
> should only be comparable to other number types.
>
> Does anyone disagree? Why?

I disagree. :)

For one, to me the bug is elsewhere in the OP's program, not at the time
of the comparison, so I'm not sure that's a good enough reason to give up
flexibility.

More importantly, though, things like "allow comparisons only to other
number types" implies a stricter class hierarchy than may exist, so the
TypeError to me feels more like a band-aid. A real solution might be to
add protocols to Python (my object is file-like object, my object is a
number-like object, etc.), and then perhaps enforce some sort of rules
that say both operands must implement a common protocol.

-Dave





More information about the Python-list mailing list