[Assorted-commits] SF.net SVN: assorted:[986] python-commons/trunk/src/commons/structs.py
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-10-05 17:18:07
|
Revision: 986 http://assorted.svn.sourceforge.net/assorted/?rev=986&view=rev Author: yangzhang Date: 2008-10-05 17:17:01 +0000 (Sun, 05 Oct 2008) Log Message: ----------- added dicts2structs, structs2dicts, tests for these; improved struct ctor Modified Paths: -------------- python-commons/trunk/src/commons/structs.py Modified: python-commons/trunk/src/commons/structs.py =================================================================== --- python-commons/trunk/src/commons/structs.py 2008-10-05 17:16:10 UTC (rev 985) +++ python-commons/trunk/src/commons/structs.py 2008-10-05 17:17:01 UTC (rev 986) @@ -5,7 +5,7 @@ Data structures: Heaps, lists, queues, and Python hacks. """ -import copy, heapq, itertools, sys +import copy, heapq, itertools, sys, unittest class bidict( object ): """Bi-directional dictionary; assumes 1:1 mappings.""" @@ -44,7 +44,8 @@ """ General-purpose namespace structure. """ - def __init__( self, **args ): + def __init__( self, d = {}, **args ): + self.__dict__.update( d ) self.__dict__.update( args ) def __repr__( self ): fields = ( '%s = %r' % ( name, value ) @@ -525,3 +526,56 @@ if self._key is not None: item = item[1] return item + +def dicts2structs(x): + """ + Given a tree of lists/dicts, perform a deep traversal to transform all the + dicts to structs. + """ + if type(x) == dict: + return free_struct( ( k, dicts2structs(v) ) for k,v in x.iteritems()) + elif type(x) == list: + return [dicts2structs(v) for v in x] + else: + return x + +def structs2dicts(x): + """ + Given a tree of lists/structs, perform a deep traversal to transform all + the structs to dicts. + """ + if type(x) == free_struct: + return dict( ( k, structs2dicts(v) ) for k,v in x.__dict__.iteritems() ) + elif type(x) == list: + return [structs2dicts(v) for v in x] + else: + return x + +# +# Tests. +# + +class common_tests(unittest.TestCase): + def test_dicts_structs(self): + dicts = { + 'atom': 0, + 'dict': { 'atom': 'atom', 'list': [1,2,3] }, + 'list': [ 'atom', {'key': 'value'} ] + } + + structs = dicts2structs(dicts) + self.assertEqual(structs.atom, dicts['atom']) + self.assertEqual(structs.dict.atom, dicts['dict']['atom']) + self.assertEqual(structs.dict.list, dicts['dict']['list']) + self.assertEqual(structs.list[0], dicts['list'][0]) + self.assertEqual(structs.list[1].key, dicts['list'][1]['key']) + + dicts2 = structs2dicts(dicts) + self.assertEqual(dicts2['atom'], structs.atom) + self.assertEqual(dicts2['dict']['atom'], structs.dict.atom) + self.assertEqual(dicts2['dict']['list'], structs.dict.list) + self.assertEqual(dicts2['list'][0], structs.list[0]) + self.assertEqual(dicts2['list'][1]['key'], structs.list[1].key) + +if __name__ == '__main__': + unittest.main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |