Welcome, guest | Sign In | My Account | Store | Cart

The deprecate decorator can be used to warn for future or current code deprecations. It accepts a message and an optional Warning class which will be passed to the warnings.warn() function.

Python, 25 lines
 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
#!/usr/bin/env python

import functools
import warnings
warnings.simplefilter("once", category=(PendingDeprecationWarning, DeprecationWarning))

def deprecate(msg, klass=PendingDeprecationWarning):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            warnings.warn(msg, klass, stacklevel=2)
            return func(*args, **kwargs)
        return wrapper
    return decorator


if __name__ == "__main__":
    @deprecate("This function will be deprecated in the future. Use new_function().")
    def old_function(a, b):
        new_function(a, b, 0)

    def new_function(a, b, c):
        print(a+b+c)

    old_function(1, 2)