2016年4月12日 星期二

[ Python 文章收集 ] How Python deprecate function by decorator

Source From Here 
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 
  1. #!/usr/bin/env python  
  2. import warnings  
  3.   
  4. def deprecated(func):  
  5.     """This is a decorator which can be used to mark functions  
  6.     as deprecated. It will result in a warning being emmitted  
  7.     when the function is used."""  
  8.     def newFunc(*args, **kwargs):  
  9.         warnings.warn("Call to deprecated function %s." % func.__name__,  
  10.                       category=DeprecationWarning,  
  11.                       stacklevel=2)  
  12.         return func(*args, **kwargs)  
  13.     newFunc.__name__ = func.__name__  
  14.     newFunc.__doc__ = func.__doc__  
  15.     newFunc.__dict__.update(func.__dict__)  
  16.     return newFunc  
  17.   
  18.   
  19.   
  20. # === Examples of use ===  
  21. @deprecated  
  22. def some_old_function(x,y):  
  23.     return x + y  
  24.   
  25. class SomeClass:  
  26.     @deprecated  
  27.     def some_old_method(self, x,y):  
  28.         return x + y  
  29.   
  30. print("Test deprecated function: %s" % (some_old_function(1,2)))  
  31. obj = SomeClass()  
  32. print("Test deprecated object func: %s" % (obj.some_old_method(1,2)))  
Execution result: 
// - W arg: Warning control. Python’s warning machinery by default prints warning messages to sys.stderr.
# python -W all Deprecated.py
Deprecated.py:30: DeprecationWarning: Call to deprecated function some_old_function.
print("Test deprecated function: %s" % (some_old_function(1,2)))
Test deprecated function: 3
Deprecated.py:32: DeprecationWarning: Call to deprecated function some_old_method.
print("Test deprecated object func: %s" % (obj.some_old_method(1,2)))
Test deprecated object func: 3


Supplement 
Python stdlib - warnings - Warning Control 
Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module...

[Python 學習筆記] 進階議題 : 修飾器 (函式修飾器)

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...