python - How to change behavior of dict() for an instance -


so i'm writing class extends dictionary right uses method "dictify" transform dict. instead though change calling dict() on object results in same behavior, don't know method override. not possible, or missing totally obvious? (and yes, know code below doesn't work hope illustrates i'm trying do.)

from collections import defaultdict  class recursivedict(defaultdict):     '''     recursive default dict.      >>> = recursivedict()     >>> a[1][2][3] = 4     >>> a.dictify()     {1: {2: {3: 4}}}     '''     def __init__(self):         super(recursivedict, self).__init__(recursivedict)      def dictify(self):         '''get standard dictionary of items in tree.'''         return dict([(k, (v.dictify() if isinstance(v, dict) else v))                      (k, v) in self.items()])      def __dict__(self):         '''get standard dictionary of items in tree.'''         print [(k, v) (k, v) in self.items()]         return dict([(k, (dict(v) if isinstance(v, dict) else v))                      (k, v) in self.items()]) 

edit: show problem more clearly:

>>> b = recursivedict() >>> b[1][2][3] = 4 >>> b defaultdict(<class '__main__.recursivedict'>, {1: defaultdict(<class '__main__.recursivedict'>, {2: defaultdict(<class '__main__.recursivedict'>, {3: 4})})}) >>> dict(b) {1: defaultdict(<class '__main__.recursivedict'>, {2: defaultdict(<class '__main__.recursivedict'>, {3: 4})})} >>> b.dictify() {1: {2: {3: 4}}} 

i want dict(b) same b.dictify()

nothing wrong approach, similar autovivification feature of perl, has been implemented in python in question. props @nosklo this.

class recursivedict(dict):     """implementation of perl's autovivification feature."""     def __getitem__(self, item):         try:             return dict.__getitem__(self, item)         except keyerror:             value = self[item] = type(self)()             return value  >>> = recursivedict() >>> a[1][2][3] = 4 >>> dict(a) {1: {2: {3: 4}}} 

edit

as suggested @rosh oxymoron, using __missing__ results in more concise implementation. requires python >= 2.5

class recursivedict(dict):     """implementation of perl's autovivification feature."""     def __missing__(self, key):         value = self[key] = type(self)()         return value 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -