Common Python Idioms

George Sakkis george.sakkis at gmail.com
Fri Dec 8 04:13:09 EST 2006


Steven D'Aprano wrote:

> On Thu, 07 Dec 2006 13:52:33 -0800, George Sakkis wrote:
>
> > I'm surprized that none of these pages mentions the incompatible type
> > comparison gotcha:
> >
> >>>> 5 < "4"
> > True
> >
> > I'm sure this has bitten many folks, particularly (ex) Perl'ers.
>
> Why is this a gotcha?
>
> I can't speak for others, but except for sorting,

Well, sorting alone is a big issue, don't you think ?

> I've never been tempted to compare ints to strings like that, but thinking about the code I've
> written, I can't think of any bad consequences that would have happened if
> I had.

Of course nobody (except perhaps from newbies coming from perl) would
intentionally compare ints with strings. The gotcha is when you compare
two values whose type you *think* you know, and since duck typing is
typically preferred over explicit type checking, it's one of the very
few cases that the "errors should never pass silently" rule is
violated. Thankfully this will raise TypeError in 3.0.

George




More information about the Python-list mailing list