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

Ruediger larudwer at freenet.de
Sat Sep 6 15:02:42 CEST 2008


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. However it can easily be done and is speeding things up
by almost an factor of 2.

Thank's again for all the help.

Rüdiger

******************************************************************

class foo(list):
    __hash__ = lambda x: id(x)

instancemethod = type(foo.__hash__)

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

def test0( obj ):
    _s_ = set()
    _s_add = _s_.add
    _s_pop = _s_.pop
    for _i_ in xrange(1000000):
        _s_add(obj())
        _s_pop()

def test1():
    return test0(foo)
def test2():
    return test0(bar)

if __name__ == '__main__':
    test1()
    test2()
    pass

******************************************************************
python -m cProfile test01.py

         6000010 function calls in 30.547 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   30.547   30.547 <string>:1(<module>)
        1    0.000    0.000   30.547   30.547 test01.py:1(<module>)
        1    0.000    0.000    0.000    0.000 test01.py:1(foo)
        2   10.784    5.392   30.547   15.273 test01.py:10(test0)
        1    0.000    0.000   19.543   19.543 test01.py:18(test1)
  1000000    4.554    0.000    6.700    0.000 test01.py:2(<lambda>)
        1    0.000    0.000   11.003   11.003 test01.py:20(test2)
        1    0.000    0.000    0.000    0.000 test01.py:6(bar)
        1    0.001    0.001   30.547   30.547 {execfile}
  1000000    2.146    0.000    2.146    0.000 {id}
  2000000    8.626    0.000   15.327    0.000 {method 'add' of 'set'objects}
  2000000    4.436    0.000    4.436    0.000 {method 'pop' of 'set'objects}




More information about the Python-list mailing list