import warnings
def deprecated(func):
def old(*args, **kwargs):
warnings.warn("That has been deprecated, use the new features!", DeprecationWarning)
return func(*args, **kwargs)
return old
@deprecated
def func():
return 10
func()
10
__getattribute__
发出警告:
我在这里使用NumPy只是为了说明原理:
import numpy as np
class MyMod(type(np)): # I could also subclass "types.ModuleType" instead ...
def __getattribute__(self, name):
if name in {'float', 'int', 'bool', 'complex'}:
warnings.warn("that's deprecated!", DeprecationWarning)
return object.__getattribute__(self, name)
np.__class__ = MyMod
np.float
PEP 562
已被接受并将添加到Python 3.7中(在编写本文时未发布),这将允许(或至少大大简化)弃用模块级常量。
__getattr__
模块中的函数。例如,在这种情况下:
import builtins
import warnings
def __getattr__(name):
if name == 'float':
warnings.warn("That has been deprecated, use the new features!", DeprecationWarning)
return builtins.float
raise AttributeError(f"module {__name__} has no attribute {name}")