Introduction
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.
How-To
Try below sample code:
- Deprecated.py
- #!/usr/bin/env python
- 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,
- stacklevel=2)
- 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
- print("Test deprecated function: %s" % (some_old_function(1,2)))
- obj = SomeClass()
- print("Test deprecated object func: %s" % (obj.some_old_method(1,2)))
Supplement
* Python stdlib - warnings - Warning Control
* [Python 學習筆記] 進階議題 : 修飾器 (函式修飾器)
沒有留言:
張貼留言