This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author t-kamiya
Recipients t-kamiya
Date 2009-09-03.08:23:47
SpamBayes Score 1.1183149e-07
Marked as misclassified No
Message-id <1251966230.42.0.696554317136.issue6830@psf.upfronthosting.co.za>
In-reply-to
Content
I found the syntax of collections.defaultdict is confusing, at least to 
me.

When I need a defaultdict of int, that is, a defaultdict which contains 
int objects, I can write simply:
a = defaultdict(int)

However, when I want a defaultdict of defaultdict of something, I can't 
write:
d = defaultdict(defaultdict(int))

This raises TypeError.

I understand the argument of defaultdict is not a type (or class), but 
a factory by definition. So I should to write:
d = defaultdict(lambda: defaultdict(int))

But this syntax is somehow confusing to me.
Am I missing some important feature of defaultdict?

The workaround that I've found is:

import collections
class __Helper(object):
  def __getitem__(self, ctor):
    return lambda: collections.defaultdict(lambda: ctor())
genericdefaultdict = __Helper()

This helper introduce some generics flavor in defaultdict.
The above cases can be spelt out:

a = genericdefaultdict[int]()
d = genericdefaultdict[genericdefaultdict[int]]()
History
Date User Action Args
2009-09-03 08:23:50t-kamiyasetrecipients: + t-kamiya
2009-09-03 08:23:50t-kamiyasetmessageid: <1251966230.42.0.696554317136.issue6830@psf.upfronthosting.co.za>
2009-09-03 08:23:48t-kamiyalinkissue6830 messages
2009-09-03 08:23:47t-kamiyacreate