views:

209

answers:

2

Hello,

Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that:

if t.index_value < len(work_list):
    ... do stuff ...
else:
    ... print some error ...

For clarification, index_value is at least zero (validated somewhere else). To my surprise, even though I know the index_value data is valid, the code keeps going to the "else:" clause. I added some ad-hoc debug code:

print('Checking whether '+str(t.index_value)+"<"+str(len(work_list)))

x = t.index_value
y = len(work_list)

print(x)
print(y)
print(x<y)

if t.index_value < len(work_list):
    ... do stuff ...
else:
    ... print some error ...

Following is the output:

>> Checking whether 3<4
>> 3
>> 4
>> False

Can anyone help me understand what's going on here?

Further clarifications:

  • work_list is a local variable instantiated within the method
  • t is a class instance, instantiated within the method ( t = SomeClass() )


Update: The problem was that the type of t.index_value was UNICODE and not int. The reason was that I deserialized the contents of t from a text file, where the value of index_value is represented by a single digit character. After I extracted it from the text, I immediately assigned it to index_value, without passing it through int() which it what I should have done, and that solved the problem.

I decided to keep the "controversial" title despite the fact it's clearly my bug and not Python's, because people with the same problem may find it using this title.

+8  A: 

In my experience, what is the type of "t.index_value"? Maybe it is a string "3".

>>> print '3' < 4
False
kcwu
That was the problem, thanks
Roee Adler
+2  A: 

To display values which might be of different types than you expect (e.g. a string rather than a number, as kcwu suggests), use repr(x) and the like.

Alex Martelli