Fast constant functions for Py2.5's defaultdict()

Giovanni Bajo noway at ask.me
Tue Feb 13 20:09:28 EST 2007


On 13/02/2007 20.01, Raymond Hettinger wrote:

> FWIW, here are three ways of writing constant functions for
> collections.defaultdict():
> 
>   d = defaultdict(int)       # slowest way; works only for zero
>   d = defaultdict(lambda: 0)   # faster way; works for any constant
>   d = defaultdict(itertools.repeat(0).next)    # fastest way; works
> for any constant
> 
> Another approach is to use the __missing__ method for dictionary
> subclasses:
> 
>   class zerodict (dict):
>       def __missing__ (self, key):
>           return 0               # fast on initial miss, but slow on
> non-misses; works for any constant
> 
> The itertools.repeat(const).next approach wins on speed and
> flexibility.

But it's the most unreadable too. I'm surprised that defaultdict(int) is 
slower than the lambda one though. What's the reason?
-- 
Giovanni Bajo



More information about the Python-list mailing list