Passed
Pull Request — master (#1079)
by Konstantin
02:32
created

ocrd_utils.deprecate   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 23
dl 0
loc 32
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A deprecation_warning() 0 2 1
A deprecated_alias() 0 11 1
A rename_kwargs() 0 13 4
1
import functools
2
import warnings
3
4
def deprecation_warning(msg, stacklevel=2):
5
    warnings.warn(msg, DeprecationWarning, stacklevel)
6
7
def deprecated_alias(**aliases):
8
    """
9
    Deprecate a kwarg in favor of another kwarg
10
    """
11
    def deco(f):
12
        @functools.wraps(f)
13
        def wrapper(*args, **kwargs):
14
            rename_kwargs(f.__name__, kwargs, aliases)
15
            return f(*args, **kwargs)
16
        return wrapper
17
    return deco
18
19
def rename_kwargs(func_name, kwargs, aliases):
20
    """
21
    https://stackoverflow.com/questions/49802412/how-to-implement-deprecation-in-python-with-argument-alias
22
    by user2357112 supports Monica
23
    """
24
    for alias, new in aliases.items():
25
        if alias in kwargs:
26
            if new in kwargs:
27
                raise TypeError('{} received both {} and {}'.format(
28
                    func_name, alias, new))
29
            warnings.warn('{} is deprecated; use {}'.format(alias, new),
30
                          DeprecationWarning)
31
            kwargs[new] = kwargs.pop(alias)
32