[New-bugs-announce] [issue6830] Some uniformness in defaultdict

Toshihiro Kamiya report at bugs.python.org
Thu Sep 3 10:23:50 CEST 2009


New submission from Toshihiro Kamiya <t-kamiya at aist.go.jp>:

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]]()

----------
components: Library (Lib)
files: ddh.py
messages: 92193
nosy: t-kamiya
severity: normal
status: open
title: Some uniformness in defaultdict
type: feature request
versions: Python 2.6
Added file: http://bugs.python.org/file14824/ddh.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6830>
_______________________________________


More information about the New-bugs-announce mailing list