2.1.2.5 函数废弃

假如我们想要在我们不再喜欢的函数第一次激活时在stderr打印废弃警告。如果我们不像修改函数,那么我们可以使用修饰器:

In [16]:

  1. class deprecated(object):
  2. """Print a deprecation warning once on first use of the function.
  3. >>> @deprecated() # doctest: +SKIP
  4. ... def f():
  5. ... pass
  6. >>> f() # doctest: +SKIP
  7. f is deprecated
  8. """
  9. def __call__(self, func):
  10. self.func = func
  11. self.count = 0
  12. return self._wrapper
  13. def _wrapper(self, *args, **kwargs):
  14. self.count += 1
  15. if self.count == 1:
  16. print self.func.__name__, 'is deprecated'
  17. return self.func(*args, **kwargs)

也可以将其实施为一个函数:

In [17]:

  1. def deprecated(func):
  2. """Print a deprecation warning once on first use of the function.
  3. >>> @deprecated # doctest: +SKIP
  4. ... def f():
  5. ... pass
  6. >>> f() # doctest: +SKIP
  7. f is deprecated
  8. """
  9. count = [0]
  10. def wrapper(*args, **kwargs):
  11. count[0] += 1
  12. if count[0] == 1:
  13. print func.__name__, 'is deprecated'
  14. return func(*args, **kwargs)
  15. return wrapper