deprecated.py 1.79 KB
Newer Older
1
2
3
4
5
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import warnings
import functools
6
7
import inspect
import sys
8

9
def deprecated(replace=None):
10
11
12
    '''This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used.'''
13
    
14
15
    warnings.resetwarnings()

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    if replace == None:
        instead = ""
    elif isinstance(replace, str) or isinstance(replace, unicode):
        instead = " " + replace
    else:
        instead = " Use %s instead." % (replace.__name__,)
    
    def real_decorator(func):
        """Nested because a decorator with a parameter has to be coded this way"""
        @functools.wraps(func)
        def new_func(*args, **kwargs):
            warnings.warn_explicit(
                "Call to deprecated function %s.%s" % (func.__name__, instead),
                category=DeprecationWarning,
                filename=func.func_code.co_filename,
                lineno=func.func_code.co_firstlineno + 1
                )
            return func(*args, **kwargs)
        return new_func
    return real_decorator
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


def module(replace=None):
    """À appeler dans un module déprécié"""

    warnings.resetwarnings()

    # On récupère le nom du module appelant la fonction
    frm = inspect.stack()[1]
    mod = inspect.getmodule(frm[0])
    if mod and mod.__name__ != '__main__':
        module_name = mod.__name__
    else:
        module_name = sys.argv[0]

    if replace == None:
        instead = ""
    elif isinstance(replace, str) or isinstance(replace, unicode):
        instead = " " + replace
    else:
        instead = " Use %s instead." % (replace.__name__,)

    warnings.warn(
        "Call to deprecated module %s.%s" % (module_name, instead),
        category=DeprecationWarning,
        stacklevel=3
    )