defaultdict of arbitrary depth
Steve Holden
steve at holdenweb.com
Fri Aug 17 01:40:35 EDT 2007
Paul McGuire wrote:
> On Aug 16, 11:19 pm, Carsten Haese <cars... at uniqsys.com> wrote:
>> On Thu, 2007-08-16 at 20:25 -0700, Paul McGuire wrote:
>>> [...]
>>> I've hacked out this recursivedefaultdict which is a
>>> defaultdict(defaultdict(defaultdict(...))), arbitrarily deep depending
>>> on the keys provided in the reference.
>>> Please comment.
>>> [...]
>>> class recursivedefaultdict(object):
>>> def __init__(self):
>>> self.__dd = defaultdict(recursivedefaultdict)
>>> def __getattr__(self,attr):
>>> return self.__dd.__getattribute__(attr)
>>> def __getitem__(self,*args):
>>> return self.__dd.__getitem__(*args)
>>> def __setitem__(self,*args):
>>> return self.__dd.__setitem__(*args)
>> This is shorter:
>>
>> from collections import defaultdict
>>
>> class recursivedefaultdict(defaultdict):
>> def __init__(self):
>> self.default_factory = type(self)
>>
>> --
>> Carsten Haesehttp://informixdb.sourceforge.net- Hide quoted text -
>>
>> - Show quoted text -
>
> Of course, very short and sweet! Any special reason you wrote:
> self.default_factory = type(self)
> instead of:
> self.default_factory = recursivedefaultdict
> ?
It's more robust under subclassing.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
More information about the Python-list
mailing list