why is self not passed to id()? <solution>

Terry Reedy tjreedy at udel.edu
Sat Sep 6 13:59:53 EDT 2008



Ruediger wrote:
> I found following solution to the problem.
> 
> Instead of assigning id directly to __hash__ it has to be wrapped with an
> instancemethod object. It is somehow strange that this doesn't happen
> automatically and it is also strange that instancemethod isn't exposed in
> the type module.

There are several internal implementation types not exposed in types 
because they are subject to change from version to version  In 3.0, your 
code does not work.  Instancemethod may to added to 3.0 or 3.1 as a 
built-in function.

> ******************************************************************
> 
> class foo(list):
>     __hash__ = lambda x: id(x)
> type
> instancemethod = type(foo.__hash__)

In 2.x, this gives you 'instancemethod'.  In 3.0, you get 'function' as 
unbound methods are no longer wrapped when the underlying function is a 
'function' (resulting from def or lambda abbreviation).

> class bar(list):
>     pass
> bar.__hash__ = instancemethod(id, None, bar)

Calling a 'function' with those parameters will not work.
Did you miss the following from my previous response?

"There *is* a third alternative, which works in this case, and which 
should be closer in speed to id.  I will leave you to do a speed test.

 >>> class bang(list):
     __hash__ = object.__hash__

 >>> s=set()
 >>> s.add(bang())
 >>> s
{[]}

  __eq__ = object.__eq__ should also work instead of the Python 
implementation I gave in my response to another response."

I would expect the already-wrapped id should work in 2.x also.

Terry Jan Reedy




More information about the Python-list mailing list