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

Java has the "@deprecated" flag (in javadocs) which is used to mark a method as no-longer-current and generates a warning if the method is used. Python can do the same thing.

Python, 27 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
26
27
import warnings

def deprecated(func):
    """This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emmitted
    when the function is used."""
    def newFunc(*args, **kwargs):
        warnings.warn("Call to deprecated function %s." % func.__name__,
                      category=DeprecationWarning)
        return func(*args, **kwargs)
    newFunc.__name__ = func.__name__
    newFunc.__doc__ = func.__doc__
    newFunc.__dict__.update(func.__dict__)
    return newFunc



# === Examples of use ===

@deprecated
def some_old_function(x,y):
    return x + y

class SomeClass:
    @deprecated
    def some_old_method(self, x,y):
        return x + y

Each function will generate a warning the first time it is used. The warnings can be suppressed in the usual way through the warnings module.

2 comments

Trent Mick 17 years, 3 months ago  # | flag

add stacklevel=2. If you add stacklevel=2 to the warnings.warn() call, then the printed warning will indicate and show the call site to the deprecated function rather than to the location of the warnings.warn() call.

Jason 9 years, 4 months ago  # | flag

Python 2.76 set "DeprecationWarning" to 'ignored' by default:

I suggest adding filter to this (as well as stack level per comment from Trent Mick):

The inner method can be replaced with the following:

def new_func(*args, **kwargs):
    warnings.simplefilter('always', DeprecationWarning)#turn off filter 
    warnings.warn("Call to deprecated function {}.".format(func.__name__),
                  category=DeprecationWarning, stacklevel=2)
    warnings.simplefilter('default', DeprecationWarning) #reset filter
    return func(*args, **kwargs)
Created by Michael Chermside on Fri, 11 Mar 2005 (PSF)
Python recipes (4591)
Michael Chermside's recipes (2)

Required Modules

Other Information and Tasks