blob: f3bcb3e72939c304c5325f3763d7f27a3b7899ed [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):
24 ret = first.copy()
25 for k,v in second.iteritems():
26 if k in ret:
27 pfn = self._policy.get((type(ret[k]), type(v)),
28 self._policy.get(None))
29 ret[k] = pfn(ret[k], v)
30 else:
31 ret[k] = v
32 return ret