admin | bae64d8 | 2013-08-01 10:50:15 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | class DictToObject( dict ): |
| 4 | def __init__( self, data = None ): |
| 5 | super( DictToObject, self ).__init__() |
| 6 | if data: |
| 7 | self.__update( data, {} ) |
| 8 | |
| 9 | def __update( self, data, did ): |
| 10 | dataid = id(data) |
| 11 | did[ dataid ] = self |
| 12 | |
| 13 | for k in data: |
| 14 | dkid = id(data[k]) |
| 15 | if did.has_key(dkid): |
| 16 | self[k] = did[dkid] |
| 17 | elif isinstance( data[k], DictToObject ): |
| 18 | self[k] = data[k] |
| 19 | elif isinstance( data[k], dict ): |
| 20 | obj = DictToObject() |
| 21 | obj.__update( data[k], did ) |
| 22 | self[k] = obj |
| 23 | obj = None |
| 24 | else: |
| 25 | self[k] = data[k] |
| 26 | |
| 27 | def __getattr__( self, key ): |
| 28 | return self.get( key, None ) |
| 29 | |
| 30 | def __setattr__( self, key, value ): |
| 31 | if isinstance(value,dict): |
| 32 | self[key] = DictToObject( value ) |
| 33 | else: |
| 34 | self[key] = value |
| 35 | |
| 36 | def update( self, *args ): |
| 37 | for obj in args: |
| 38 | for k in obj: |
| 39 | if isinstance(obj[k],dict): |
| 40 | self[k] = DictToObject( obj[k] ) |
| 41 | else: |
| 42 | self[k] = obj[k] |
| 43 | return self |
| 44 | |
| 45 | def merge( self, *args ): |
| 46 | for obj in args: |
| 47 | for k in obj: |
| 48 | if self.has_key(k): |
| 49 | if isinstance(self[k],list) and isinstance(obj[k],list): |
| 50 | self[k] += obj[k] |
| 51 | elif isinstance(self[k],list): |
| 52 | self[k].append( obj[k] ) |
| 53 | elif isinstance(obj[k],list): |
| 54 | self[k] = [self[k]] + obj[k] |
| 55 | elif isinstance(self[k],DictToObject) and isinstance(obj[k],Object): |
| 56 | self[k].merge( obj[k] ) |
| 57 | elif isinstance(self[k],DictToObject) and isinstance(obj[k],dict): |
| 58 | self[k].merge( obj[k] ) |
| 59 | else: |
| 60 | self[k] = [ self[k], obj[k] ] |
| 61 | else: |
| 62 | if isinstance(obj[k],dict): |
| 63 | self[k] = DictToObject( obj[k] ) |
| 64 | else: |
| 65 | self[k] = obj[k] |
| 66 | return self |
Jon Hall | 4ba53f0 | 2015-07-29 13:07:41 -0700 | [diff] [blame] | 67 | |