November 8, 2016

Python - deprecating APIs

Decorators facilitate an easy way to let users know that a given method is deprecated. You can even point users to the method they should be using instead. This is done by using decorators that accept arguments.

The code below demonstrates this,

import warnings

def deprecated(replaced_by_func):  
    def wrap(f):
        def new_func(*args, **kwargs):
            warnings.simplefilter('always', DeprecationWarning)
            warnings.warn(
                "Call to deprecated function " + f.__name__ +
                ". This method is replaced by " + replaced_by_func.__name__,
                category=DeprecationWarning, stacklevel=2)
            warnings.simplefilter('default', DeprecationWarning)
            return f(*args, **kwargs)
        new_func.__dict__.update(f.__dict__)
        new_func.__doc__ = f.__doc__
        new_func.__name__ = f.__name__
        return new_func
    return wrap


def new_method(a, b):  
    return a + b

@deprecated(new_method)
def some_old_method(a, b):  
    return a + b

some_old_method(42+42)  

When the above code is executed, you would receive a warning stating some_old_method is deprecated, and to use new_method instead.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket