R
Raymond Hettinger
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.
Raymond
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.
Raymond