@andymitchhank/

deprecated_decorator

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from functools import wraps
import logging
from typing import Callable, Tuple, Dict, Any

logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', level=logging.DEBUG)
logger = logging.getLogger()


def format_args(*args, **kwargs):
    """ Helper function to prettify arg lists """

    args = ', '.join(repr(arg) for arg in args)
    kwargs = ', '.join([f'{k}: {repr(v)}' for k, v in kwargs.items()])

    if args and kwargs: 
        return f'{args}, {kwargs}'
 
    if args:
        return f'{args}'
 
    return f'{kwargs}'


def deprecated(forward_func=None, arg_mapper:Callable[[Any], Tuple[Tuple, Dict]]=None):
    """ A function that returns a function that takes a function... yup """
    
    def wrapper(func):
    
        @wraps(func)
        def inner(*args, **kwargs):
            if not forward_func:
                logger.info(f'{func.__name__} is deprecated')

            old_args = format_args(*args, **kwargs)
            if arg_mapper:
                args, kwargs = arg_mapper(*args, **kwargs)
            new_args = format_args(*args, **kwargs)

            if forward_func: 
                logger.info(f'forwarding {func.__name__}({old_args}) to {forward_func.__name__}({new_args})')
                return forward_func(*args, **kwargs)

            return func(*args, **kwargs)

        return inner

    return wrapper


def the_replacement_function(x: int, y: int, z: int):
    print(z, y, x)


@deprecated()
def a_deprecated_function(x: int, y: int, z: int):
    print(x, y, z)


@deprecated(forward_func=the_replacement_function)
def forwarded_deprecated_function(x: int, y: int, z: int):
    print(x, y, z)


def arg_mapper(s: str):
    return tuple(int(i) for i in s.split(',')), {}
     

@deprecated(the_replacement_function, arg_mapper)
def forwarded_with_mapper(s: str):
     x, y, z = (int(i) for i in s.split(','))
     print(x, y, z)


a_deprecated_function(1, 2, 3)
forwarded_deprecated_function(1, 2, 3)
forwarded_with_mapper('1,2,3')