Modules are hashable?!

Sam Holden sholden at flexal.cs.usyd.edu.au
Fri Sep 3 00:32:42 EDT 2004


On Fri, 03 Sep 2004 04:05:40 GMT, Maurice LING <mauriceling at acm.org> wrote:
> Alex Martelli wrote:
>
>> Leif K-Brooks <eurleif at ecritters.biz> wrote:
>> 
>> 
>>>I was just playing around, and noticed that modules seem to be hashable.
>>>Can anyone explain that, especially given the fact that they're mutable?
>> 
>> 
>> Any object x is hashable if type(x) does not expose __eq__ nor __cmp__.
>> In that case, the meaning of x==y for that object is 'x is y', that is,
>> id(x)==id(y), so having hash(x) return id(x) is perfectly functional.
>> Mutation is not a problem if it doesn't affect equality comparisons.
>> 
>> 
>> Alex
>
> The idea that I get from reading this thread is that objects that can be 
> type compared (comparing the contents) are not hashable, and they are 
> list, strings, tuples and dictionary. Is there any others that fall into 
> this category? Is there any way to make them hashable?

Define the __hash__ method for the class.

Strings for example, are hashable even though they comparisons are done
with respect to the contents and not the id. Tuples are also:

; python
Python 2.3.4 (#2, Aug 18 2004, 13:18:19) 
[GCC 3.3.4 (Debian 1:3.3.4-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t1 = (1,2,3)
>>> t2 = (1,2,3)
>>> id(t1)
1075806412
>>> id(t2)
1075841140
>>> hash(t1)
-821448277
>>> hash(t2)
-821448277
>>> 
;

-- 
Sam Holden



More information about the Python-list mailing list