@@ -15,7 +15,7 @@ def wrapper(*args, **kwargs):
15
15
return wrapper
16
16
17
17
18
- def deprecate_kwarg (old_arg_name , new_arg_name ):
18
+ def deprecate_kwarg (old_arg_name , new_arg_name , mapping = None ):
19
19
"""Decorator to deprecate a keyword argument of a function
20
20
21
21
Parameters
@@ -24,14 +24,18 @@ def deprecate_kwarg(old_arg_name, new_arg_name):
24
24
Name of argument in function to deprecate
25
25
new_arg_name : str
26
26
Name of prefered argument in function
27
+ mapping : dict or callable
28
+ If mapping is present, use it to translate old arguments to
29
+ new arguments. A callable must do its own value checking;
30
+ values not found in a dict will be forwarded unchanged.
27
31
28
32
Examples
29
33
--------
30
34
The following deprecates 'cols', using 'columns' instead
31
35
32
36
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
33
37
... def f(columns=''):
34
- ... print columns
38
+ ... print( columns)
35
39
...
36
40
>>> f(columns='should work ok')
37
41
should work ok
@@ -41,22 +45,46 @@ def deprecate_kwarg(old_arg_name, new_arg_name):
41
45
should raise warning
42
46
>>> f(cols='should error', columns="can't pass do both")
43
47
TypeError: Can only specify 'cols' or 'columns', not both
48
+ >>> @deprecate_kwarg('old', 'new', {'yes': True, 'no', False})
49
+ ... def f(new=False):
50
+ ... print('yes!' if new else 'no!')
51
+ ...
52
+ >>> f(old='yes')
53
+ FutureWarning: old='yes' is deprecated, use new=True instead
54
+ warnings.warn(msg, FutureWarning)
55
+ yes!
44
56
45
57
"""
58
+ if mapping is not None and not hasattr (mapping , 'get' ) and \
59
+ not callable (mapping ):
60
+ raise TypeError ("mapping from old to new argument values "
61
+ "must be dict or callable!" )
46
62
def _deprecate_kwarg (func ):
47
63
@wraps (func )
48
64
def wrapper (* args , ** kwargs ):
49
65
old_arg_value = kwargs .pop (old_arg_name , None )
50
66
if old_arg_value is not None :
51
- msg = "the '%s' keyword is deprecated, use '%s' instead" % \
52
- (old_arg_name , new_arg_name )
67
+ if mapping is not None :
68
+ if hasattr (mapping , 'get' ):
69
+ new_arg_value = mapping .get (old_arg_value ,
70
+ old_arg_value )
71
+ else :
72
+ new_arg_value = mapping (old_arg_value )
73
+ msg = "the %s=%r keyword is deprecated, " \
74
+ "use %s=%r instead" % \
75
+ (old_arg_name , old_arg_value ,
76
+ new_arg_name , new_arg_value )
77
+ else :
78
+ new_arg_value = old_arg_value
79
+ msg = "the '%s' keyword is deprecated, " \
80
+ "use '%s' instead" % (old_arg_name , new_arg_name )
53
81
warnings .warn (msg , FutureWarning )
54
82
if kwargs .get (new_arg_name , None ) is not None :
55
83
msg = "Can only specify '%s' or '%s', not both" % \
56
84
(old_arg_name , new_arg_name )
57
85
raise TypeError (msg )
58
86
else :
59
- kwargs [new_arg_name ] = old_arg_value
87
+ kwargs [new_arg_name ] = new_arg_value
60
88
return func (* args , ** kwargs )
61
89
return wrapper
62
90
return _deprecate_kwarg
0 commit comments