default behavior

Peter Otten __peter__ at web.de
Fri Jul 30 06:21:39 EDT 2010


Duncan Booth wrote:

> Peter Otten <__peter__ at web.de> wrote:
> 
>>>>> from collections import defaultdict
>>>>> d = defaultdict(1 .conjugate)
>>>>> d["x"] += 2
>>>>> d["x"]
>> 3
>> 
>> Isn't that beautiful? Almost like home;)
>> 
>> It is also fast:
>> 
>> $ python -m timeit -s"one = lambda: 1" "one()"
>> 1000000 loops, best of 3: 0.213 usec per loop
>> $ python -m timeit -s"one = 1 .conjugate" "one()"
>> 10000000 loops, best of 3: 0.0972 usec per loop
>> 
>> Micro-optimisation, the best excuse for ugly code...
>> 
> 
> Nice one, but if you are going to micro-optimise why not save a few
> keystrokes while you're at it and use '1 .real' instead?

>>> 1 .real
1
>>> 1 .conjugate
<built-in method conjugate of int object at 0x1734298>
>>> 1 .conjugate()

real is a property, not a method. conjugate() was the first one that worked 
that was not __special__. I think it has the added benefit that it's likely 
to confuse the reader...

Peter



More information about the Python-list mailing list