Skip to content Skip to sidebar Skip to footer

Hash A Python New-style Class Instance?

Given a custom, new-style python class instance, what is a good way to hash it and get a unique ID-like value from it to use for various purposes? Think md5sum or sha1sum of a giv

Solution 1:

That depends entirely on what properties the ID should have.

For instance, you can use id(foo) to get an ID which is guaranteed to be unique as long as foo is active in memory, or you could use repr(instance.__dict__) if all of the fields have sensible repr values.

What specifically do you need it for?

Solution 2:

While you're using hexdigests of pickles at the moment, you make it sound like the id doesn't actually need to be related to the object, it just needs to be unique. Why not simply use the uuid module, specifically uuid.uuid4 to generate unique IDs and assign them to a uuid field in the object...

Post a Comment for "Hash A Python New-style Class Instance?"