Here is another solution:
This decorator (actually a decorator factory ) allows you to send the reason for the message. It is also more useful to help the developer diagnose the problem by specifying the original file name and line number .
EDIT : this code uses the null recommendation: replace the warnings.warn_explicit line with warnings.warn(msg, category=DeprecationWarning, stacklevel=2) , which prints the function call site, not the function definition site. This makes debugging easier.
EDIT2 : This version allows the developer to specify an optional βcauseβ message.
import functools import inspect import warnings string_types = (type(b''), type(u'')) def deprecated(reason): """ 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. """ if isinstance(reason, string_types):
You can use this decorator for functions , methods, and classes .
Here is a simple example:
@deprecated("use another function") def some_old_function(x, y): return x + y class SomeClass(object): @deprecated("use another method") def some_old_method(self, x, y): return x + y @deprecated("use another class") class SomeOldClass(object): pass some_old_function(5, 3) SomeClass().some_old_method(8, 9) SomeOldClass()
You'll get:
deprecated_example.py:59: DeprecationWarning: Call to deprecated function or method some_old_function (use another function). some_old_function(5, 3) deprecated_example.py:60: DeprecationWarning: Call to deprecated function or method some_old_method (use another method). SomeClass().some_old_method(8, 9) deprecated_example.py:61: DeprecationWarning: Call to deprecated class SomeOldClass (use another class). SomeOldClass()
EDIT3: This decorator is now part of an obsolete library:
New stable version v1.2.6 π
Laurent LAPORTE Oct 28 '16 at 8:55 2016-10-28 08:55
source share