Is there a unique object identifier in Python

This will be similar to the java.lang.Object.hashcode() method.

I need to store objects that I have no control over, and make sure that only if two objects are actually the same object (do not contain the same values), the values ​​will be overwritten.

+62
python
Aug 09 '09 at 21:40
source share
4 answers
 id(x) 

will do the trick for you. But I'm curious what is wrong with respect to a set of objects (which combines objects by value)?

For your specific problem, I would probably keep a set of identifiers or wrapper objects. The wrapper object will contain one link and compare with x==y <==> x.ref is y.ref .

It's also worth noting that Python objects also have a hash function. This function is required to place an object in a collection or dictionary. It is assumed that it sometimes collides for different objects, although good hash implementations try to make it less likely.

+97
Aug 9 '09 at 21:42
source share

What " is " for.

Instead of testing " if a == b ", which checks for the same value,

test " if a is b ", which will check the same identifier.

+29
Aug 09 '09 at 21:43
source share

As ilya n mentions, id (x) creates a unique identifier for the object.

But your question is confusing, as the hashCode Java method does not give a unique identifier. Java hashCode works like most hash functions: it always returns the same value for the same object, two identical objects always get the same codes, and unequal hash values ​​imply unequal hash codes. In particular, two different and unequal objects can receive the same value.

This is confusing because the cryptographic hash functions are very different from this and are more similar (albeit not quite) to the "unique identifier" that you requested.

The Python equivalent of the hashCode Java method is hash (x).

+2
Aug 09 '09 at 21:48
source share

You do not need to compare objects before placing them in a set. set () will already take care of this.

  class A(object): a = 10 b = 20 def __hash__(self): return hash((self.a, self.b)) a1 = A() a2 = A() a3 = A() a4 = a1 s = set([a1,a2,a3,a4]) s => set([<__main__.A object at 0x222a8c>, <__main__.A object at 0x220684>, <__main__.A object at 0x22045c>]) 

Note. You really don't need to redefine the hash to prove this :-)

-one
Jan 14 '15 at 6:17
source share



All Articles