blob: 01dfccb9a95e986d2c5453370b548e7240081a7e [file] [log] [blame]
martin f. krafftf37f0682013-06-14 16:36:20 +02001#
2# -*- coding: utf-8 -*-
3#
4# This file is part of reclass (http://github.com/madduck/reclass)
5#
6# Copyright © 2007–13 martin f. krafft <madduck@madduck.net>
7# Released under the terms of the Artistic Licence 2.0
8#
9from base import BaseDictMerger
10
11class DictRecursivePolicyUpdate(BaseDictMerger):
12
13 def __init__(self, policy=None):
14 super(DictRecursivePolicyUpdate, self).__init__()
15 if policy is None:
16 policy = {(dict,dict) : self.merge,
17 (list,list) : lambda x,y: x+y,
18 (dict,list) : lambda x,y: self.merge(x, dict(y)),
19 None : lambda x,y: y
20 }
21 self._policy = policy
22
23 def merge(self, first, second):
martin f. kraffta95eaa32013-06-16 11:56:41 +020024 if second is None:
25 return first
26
martin f. krafftf37f0682013-06-14 16:36:20 +020027 ret = first.copy()
28 for k,v in second.iteritems():
29 if k in ret:
30 pfn = self._policy.get((type(ret[k]), type(v)),
31 self._policy.get(None))
32 ret[k] = pfn(ret[k], v)
33 else:
34 ret[k] = v
35 return ret