Welcome, guest | Sign In | My Account | Store | Cart
```#!/usr/bin/env python

"""
Deprecated decorator.

Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
"""

import warnings

def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.

>>> @deprecated()
... def foo(x):
...     return x
...
>>> ret = foo(1)
DeprecationWarning: foo is deprecated
>>> ret
1
>>>
>>>
>>> def newfun(x):
...     return 0
...
>>> @deprecated(newfun)
... def foo(x):
...     return x
...
>>> ret = foo(1)
DeprecationWarning: foo is deprecated; use newfun instead
>>> ret
0
>>>
"""
def outer(oldfun):
def inner(*args, **kwargs):
msg = "%s is deprecated" % oldfun.__name__
if replacement is not None:
msg += "; use %s instead" % (replacement.__name__)
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if replacement is not None:
return replacement(*args, **kwargs)
else:
return oldfun(*args, **kwargs)
return inner
return outer

if __name__ == '__main__':

# --- new function
def sum_many(*args):
return sum(args)

# --- old / deprecated function
@deprecated(sum_many)
def sum_couple(a, b):
return a + b

print sum_couple(2, 2)
```

#### Diff to Previous Revision

```--- revision 1 2011-08-02 19:37:04
+++ revision 2 2011-12-03 09:52:08
@@ -53,9 +53,11 @@

if __name__ == '__main__':

+    # --- new function
def sum_many(*args):
return sum(args)

+    # --- old / deprecated function
@deprecated(sum_many)
def sum_couple(a, b):
return a + b
```