1
2
3
4
5
6
7
8
9 """Helpers for arguments handling."""
10
11 __docformat__ = 'restructuredtext'
12
14 """Helper to separate kwargs into multiple groups
15
16 :Parameters:
17 prefixes : list of basestrings
18 Each entry sets a prefix which puts entry with key starting
19 with it into a separate group.
20 Group '' corresponds to 'leftovers'
21
22 :Output:
23 dictionary with keys == `prefixes`
24 """
25 if not ('' in prefixes):
26 prefixes = prefixes + ['']
27 result = [ [] for i in prefixes ]
28 for k,v in kwargs.iteritems():
29 for i,p in enumerate(prefixes):
30 if k.startswith(p):
31 result[i].append((k.replace(p,'',1), v))
32 break
33 resultd = dict((p,dict(x)) for p,x in zip(prefixes, result))
34 return resultd
35
36
38 """Decorator function to join parts of kwargs together
39
40 :Parameters:
41 prefixes : list of basestrings
42 Prefixes to split based on. See `split_kwargs`
43 assign : bool
44 Flag to assign the obtained arguments to self._<prefix>_kwargs
45 passthrough : bool
46 Flag to pass joined arguments as <prefix>_kwargs argument.
47 Usually it is sufficient to have either assign or passthrough.
48 If none of those is True, decorator simply filters out mentioned
49 groups from being passed to the method
50
51 Example: if needed to join all args which start with 'slave<underscore>'
52 together under slave_kwargs parameter
53 """
54 def decorated_method(method):
55 def do_group_kwargs(self, *args_, **kwargs_):
56 if '' in prefixes:
57 raise ValueError, \
58 "Please don't put empty string ('') into prefixes"
59
60 splits = split_kwargs(kwargs_, prefixes)
61
62 kwargs__ = splits['']
63 for prefix in prefixes:
64 skwargs = splits[prefix]
65 k = '%skwargs' % prefix
66 if k in kwargs__:
67
68 raise ValueError, '%s is already given in the arguments' % k
69 if passthrough: kwargs__[k] = skwargs
70 if assign: setattr(self, '_%s' % k, skwargs)
71 return method(self, *args_, **kwargs__)
72 do_group_kwargs.func_name = method.func_name
73 return do_group_kwargs
74
75 return decorated_method
76