defaultdict of arbitrary depth

Paul McGuire ptmcg at austin.rr.com
Fri Aug 17 06:27:11 CEST 2007


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
?


-- Paul




More information about the Python-list mailing list