'20' <= 100 
Author Message
 '20' <= 100

I have a statement somewhere in the code that
boils down to comparing a string object with an integer.
i.e.  var1 <= var2
where var1 = '20' and var2 = 100

The code runs ok but the above comparison always return 0 !!

It took me quite an effort to finally pin it down.

Is it the programmer's responsibility to check the
type of var1 and var2 before using <=   ???

--HP



Tue, 18 Oct 2005 05:58:00 GMT  
 '20' <= 100

Quote:
> boils down to comparing a string object with an integer.
> i.e.  var1 <= var2
> where var1 = '20' and var2 = 100

> The code runs ok but the above comparison always return 0 !!

> It took me quite an effort to finally pin it down.

> Is it the programmer's responsibility to check the
> type of var1 and var2 before using <=   ???

Short answer:  Yes.

Long answer:  Why check, just coerce to what you need.
    int(var1) <= int(var2)
    str(var1) <= str(var2)
    # Note, these can give different answers
    # You're probably looking for the first one

Raymond Hettinger



Tue, 18 Oct 2005 06:45:47 GMT  
 '20' <= 100

Quote:

> I have a statement somewhere in the code that
> boils down to comparing a string object with an integer.
> i.e.  var1 <= var2
> where var1 = '20' and var2 = 100

> The code runs ok but the above comparison always return 0 !!

> It took me quite an effort to finally pin it down.

> Is it the programmer's responsibility to check the
> type of var1 and var2 before using <=   ???

No, but it _is_ the programmer's responsibility to understand that data
that's being processed. :)

There's no way for python to magically guess it for you - the bug in your
program isn't that you didn't check the type but that you're not operating
on the type of data you think you're operating on (it's a slightly
higher-level bug).

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'?

-Dave



Tue, 18 Oct 2005 07:57:32 GMT  
 '20' <= 100

Quote:

> I have a statement somewhere in the code that
> boils down to comparing a string object with an integer.
> i.e.  var1 <= var2
> where var1 = '20' and var2 = 100

> The code runs ok but the above comparison always return 0 !!

> It took me quite an effort to finally pin it down.

I'd prefer Python to raise an exception if you compare a number to
something non-numeric.

Quote:
> Is it the programmer's responsibility to check the
> type of var1 and var2 before using <=   ???

Apparently :-( You can use asserts if you want to catch such errors:

assert type(t1) is int

I tend to have quite some

assert obj is not None

in my code, too.

Combined with unit tests, you have better chances that bugs like yours
are caught earlier.

-- Gerhard



Tue, 18 Oct 2005 06:18:40 GMT  
 '20' <= 100

Quote:

> [...] 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.

strings should only be comparable to other basestrings and numbers
should only be comparable to other number types.

Does anyone disagree? Why?

-- Gerhard



Tue, 18 Oct 2005 06:22:25 GMT  
 '20' <= 100

Quote:


> > [...] 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.

Quote:
> 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



Tue, 18 Oct 2005 08:34:07 GMT  
 '20' <= 100

Quote:

>> i.e.  var1 <= var2
>> where var1 = '20' and var2 = 100

> I'd prefer Python to raise an exception if you compare a number to
> something non-numeric.

For '<', '<=', '>' and '>=' I agree, but for '==' and '!=' I very much
disagree since they have an obvious easy-to-define meaning (i.e.
that objects of incompatible types are different). As I understand it
'<' etc can produce exceptions these days, does anyone know if '=='
and '!=' can (in the absence of any weird non-standard user-defined
classes overriding __cmp__ or somesuch)?


Tue, 18 Oct 2005 07:08:24 GMT  
 '20' <= 100


Quote:

> > [...] 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.

> strings should only be comparable to other basestrings and numbers
> should only be comparable to other number types.

> Does anyone disagree? Why?

I'm sure you remember this dead horse being flogged numerous
times in the past. The upshot is that sort needs a reliable method
of ordering heterogenous objects.

I wouldn't mind having both a "strict" and a "non-strict" comparison,
but that would be enough of a major language change that it would
need quite a bit of discussion.

John Roth

- Show quoted text -

Quote:

> -- Gerhard



Tue, 18 Oct 2005 07:19:06 GMT  
 '20' <= 100
[Gerhard H?ring]

Quote:
>> I'd prefer Python to raise an exception if you compare a number to
>> something non-numeric.

[Jon Ribbens]

Quote:
> For '<', '<=', '>' and '>=' I agree, but for '==' and '!=' I very much
> disagree since they have an obvious easy-to-define meaning (i.e.
> that objects of incompatible types are different).

That seems the best rule when it applies, and, e.g., 2.3's new datetime- and
set- module types try to live by that:

Quote:
>>> from datetime import date
>>> t = date.today()
>>> t == 3
False
>>> t > 3

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't compare datetime.date to int

Quote:

>>> from sets import Set
>>> s = Set()
>>> s == 3
False
>>> s > 3

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\CODE\PYTHON\lib\sets.py", line 305, in __gt__
    self._binary_sanity_check(other)
  File "C:\CODE\PYTHON\lib\sets.py", line 314, in _binary_sanity_check
    raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets

A problem is that "incompatible types" isn't always the right distinction:

Quote:
> As I understand it '<' etc can produce exceptions these days, does
> anyone know if '==' and '!=' can (in the absence of any weird non-
> standard user-defined classes overriding __cmp__ or somesuch)?

They can, and one particular case is common among people playing with
Unicode but still trying to mix it with 8-bit strings:

Quote:
>>> u'xyz' == 'xyz'

True

Quote:
>>> u'xyz' == chr(140)

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8c in position 0:
ordinal ot in range(128)

The first example shows that str and unicode can be compared for equality
successfully.  The second shows that whether they can depends not on the
types, but on the specific values being compared.



Tue, 18 Oct 2005 07:32:42 GMT  
 '20' <= 100

Quote:

> I'm sure you remember this dead horse being flogged numerous
> times in the past. The upshot is that sort needs a reliable method
> of ordering heterogenous objects.

But, it doesn't have one.  Comparing a complex number to
anything raises an exception.  

Isn't there also something about comparing two strings of
different encodings also raising an exception?

--
Grant Edwards                   grante             Yow!  .. over in west
                                  at               Philadelphia a puppy is
                               visi.com            vomiting...



Tue, 18 Oct 2005 09:15:46 GMT  
 '20' <= 100


Wed, 18 Jun 1902 08:00:00 GMT  
 '20' <= 100

Quote:

> 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"

It may be well-documented, but it's counterintuitive.  If str + int is
an error, then why isn't str < int (besides backward compatibility)?

Quote:
> > 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,

But an exception would at least make it obvious that a bug exists,
instead of letting it pass silently.


Tue, 18 Oct 2005 12:29:59 GMT  
 '20' <= 100


Wed, 18 Jun 1902 08:00:00 GMT  
 '20' <= 100


Quote:

> > I'm sure you remember this dead horse being flogged numerous
> > times in the past. The upshot is that sort needs a reliable method
> > of ordering heterogenous objects.

> But, it doesn't have one.  Comparing a complex number to
> anything raises an exception.

Which has also been complained about in the context of sorts.

Quote:

> Isn't there also something about comparing two strings of
> different encodings also raising an exception?

Hadn't heard that one, and I don't understand why it would
do so. Unless I've missed something completely, strings
don't carry encoding information with them. They're either
unicode or single byte, and the latter can always be converted
to the former for comparison purposes.

John Roth

Quote:

> --
> Grant Edwards                   grante             Yow!  .. over in
west
>                                   at               Philadelphia a
puppy is
>                                visi.com            vomiting...



Tue, 18 Oct 2005 22:59:36 GMT  
 '20' <= 100

Quote:

> Does anyone disagree? Why?

Yes.  sort.  In order to sort heterogenous, lists cmp must work on mixed
type pairs.

--

"It turns out that a decimal point by itself is equivalent to '0.0'.  Let's
 hope people don't use that fact." Donald Knuth (in the TeX source)



Tue, 18 Oct 2005 22:54:48 GMT  
 
 [ 22 post ]  Go to page: [1] [2]

 Relevant Pages 

1. httplib and '100 Continue' after POST

2. Don't Forget: Tcl'2002 is September 16-20

3. Clipper Summer'87 cpu load 100%

4. What's happening with my P-100?

5. Generating 100's of Objects

6. Les Nouvelles d'APL : n 20

7. APP GPF's after 20 mins

8. C5ee, ODBC and SQLserver: Decimal(39,20)

9. Exe with 20 dll's loads slow

 

 
Powered by phpBB® Forum Software