Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You don't need all that stuff:</p> <pre><code>from functools import wraps import warnings def deprecated(message, newfunc): def _deprecated(func): @wraps(func) def _wrapped(*args, **kwds): warnings.warn(message + ', ' + newfunc, DeprecationWarning, stacklevel=2) return func(*args, **kwds) return _wrapped return _deprecated </code></pre> <hr> <p><strong>That's all</strong>! Check it out:</p> <pre><code>@deprecated("function foo is deprecated", "use bar instead") def foo(bar): print 'Hello', bar foo('World') </code></pre> <p>I get </p> <pre><code>teste.py:17: DeprecationWarning: function foo is deprecated, use bar instead foo('World') Hello World </code></pre> <hr> <p>Another example:</p> <pre><code>class Foo(object): @deprecated("method bar is deprecated", "use baz instead") def bar(self, baz): print 'Goodbye', baz f = Foo() f.bar('World') </code></pre> <p>I get:</p> <pre><code>teste.py:25: DeprecationWarning: method bar is deprecated, use baz instead f.bar('World') Goodbye World </code></pre> <p>The secret is the <code>stacklevel</code> parameter to <code>warnings.warn</code>. The <a href="http://docs.python.org/library/warnings#warnings.warn" rel="noreferrer">docs</a> say:</p> <blockquote> <p><em>The stacklevel argument can be used by wrapper functions written in Python, (...) makes the warning refer to deprecation()‘s caller, rather than to the source of deprecation() itself (since the latter would defeat the purpose of the warning message).</em></p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload