Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique ID for python object based on its attributes

Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example,

class test:
    def __init__(self, name):
        self.name = name

obj1 = test('a')
obj2 = test('a')

hash1 = magicHash(obj1)
hash2 = magicHash(obj2)

What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.

like image 441
cdwilson Avatar asked Aug 24 '09 22:08

cdwilson


People also ask

How do you create a unique id in Python?

creating a unique random id To create a random id, you call the uuid4 () method and it will automatically generate a unique id for you just as shown in the example below; Example of usage.

Is an id unique python?

The id is unique only as long as an object is alive. Objects that have no references left to them are removed from memory, allowing the id() value to be re-used for another object, hence the non-overlapping lifetimes wording. Note that this applies to CPython only, the standard implementation provided by python.org.

How do you find the id of an object in Python?

Python id() FunctionThe id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.


1 Answers

You mean something like this? Using the special method __hash__

class test:
     def __init__(self, name):
         self.name = name
     def __hash__(self):
         return hash(self.name)

>>> hash(test(10)) == hash(test(20))
False
>>> hash(test(10)) == hash(test(10))
True
like image 131
Nadia Alramli Avatar answered Oct 13 '22 18:10

Nadia Alramli