The '==' operator is not working correctly in Python

Question:

The following piece of code is behaving incorrectly in my script:

from ctypes import *

base_addr = c_uint64(0)
base_addr_temp = c_uint64(0)
print base_addr
print base_addr_temp
if(base_addr == base_addr_temp):
    print "val"

The output that I get:

c_ulong(0L)

c_ulong(0L)

I am using Python version 2.7.3.

Asked By: Dexter

||

Answers:

I think that because these are objects, you’d have to compare them by value:

base_addr.value == base_addr_temp.value

It’s been a while since I’ve done any Python, but in many languages, two objects are only considered “equal” if they actually refer to the same object (i.e. reference the same location in memory).

Answered By: Thomas Kelley

Your comparison is between the addresses of two objects ("base_addr" and "base_addr_temp"), not between the values of your two objects (which are both 0L).

Weirdly, on Windows and using Python 2.7.3, base_addr.str() returns ‘c_ulonglong(0L)’ which is different from what you saw, but that doesn’t change the fact that you were comparing data locations rather than values.

Answered By: bjorke
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.