Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using object id as a hash for objects in Python

Tags:

python

hash

Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.

This occurred to me while looking at Sets of instances and I'm wondering if it's wise.

like image 492
Noufal Ibrahim Avatar asked Jan 11 '10 05:01

Noufal Ibrahim


People also ask

What is the difference between id and hash in Python?

Unequal objects may have the same hash values. Equal objects need to have the same id values. Whenever obj1 is obj2 is called, the id values of both objects is compared, not their hash values.

What is __ hash __ for in Python?

Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary.

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

For most Python classes this is the default behaviour. The unhashable ones are unhashable for a good reason: they are mutable collections.

For collections it is practical to have the equality relation (as defined by __eq__()) based on equality of their contents. This, and the requirement for __hash__() to be consisent with equality, would of course make the __hash__() mutable, which would be horrible for collections containing such objects.

So you can do this but it costs you the content-based equality relation.

like image 102
Rafał Dowgird Avatar answered Oct 31 '22 18:10

Rafał Dowgird