如何在python中声明一个不推荐使用的模块

sau*_*rbh 12 python module deprecated

如何在python中声明一个不推荐使用的模块?

我想要在导入特定模块或调用其任何函数时打印警告.

aba*_*ert 12

你想要warn一个DeprecationWarning.

你究竟如何调用它并不重要,但stdlib有一个不推荐使用的模块的标准模式,如下所示:

# doc string, top-level comments, imports, __all__ =

import warnings
warnings.warn("the spam module is deprecated", DeprecationWarning,
              stacklevel=2)

# normal module code
Run Code Online (Sandbox Code Playgroud)

有关示例,请参见2.7 sets源代码.

  • 我在特定模块的 __init.py__ 中使用了这段代码,我希望将其显示为已弃用。它不起作用,也没有出错。该模块的函数和类可以轻松访问。 (3认同)