2 from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
5 'A simple namespace object.'
6 def __init__(self, d = {}, **kwargs):
7 'd is the dictionary to update my __dict__ with.'
8 self.__dict__.update(d)
9 self.__dict__.update(kwargs)
13 Given a tree of lists/dicts, perform a deep traversal to transform all the
17 return struct((k, dicts2struct(v)) for k,v in x.iteritems())
19 return [dicts2struct(v) for v in x]
24 # Hacks to work around lack of Python 2.5's `with` statement.
27 def with_closing(rsrc):
29 Utility to emulate Python 2.5's `with closing(rsrc)` context manager.
32 @with_closing(file('/tmp/foo'))
35 # now 'contents' is the contents of /tmp/foo
38 try: return func(rsrc)
42 def with_lock_file(path, exclusive = True):
44 Context manager for lock files. Example:
46 @with_lock_file('/tmp/mylock')
51 print input # prints what raw_input() returned
54 @with_closing(file(path, 'w'))
56 if exclusive: locktype = LOCK_EX
57 else: locktype = LOCK_SH
60 finally: flock(f, LOCK_UN)
68 class common_tests(unittest.TestCase):
69 def test_dicts2structs(self):
72 'dict': { 'atom': 'atom', 'list': [1,2,3] },
73 'list': [ 'atom', {'key': 'value'} ]
75 structs = dicts2struct(dicts)
76 self.assertEqual(structs.atom, dicts['atom'])
77 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
78 self.assertEqual(structs.dict.list, dicts['dict']['list'])
79 self.assertEqual(structs.list[0], dicts['list'][0])
80 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
82 if __name__ == '__main__':