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.
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.
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: