1

我们有一个应用程序,它的用户可以使用插件对其进行扩展。我们提供了一些帮助模块,因此用户可以从他们的插件中访问它们

import helpermodule

现在我们决定最好更改辅助模块的包装,以便所有这些都从主包中加载,如下所示:

from ourpackage import helpermodule

由于我们不想破坏用户插件中的现有代码,我们仍然提供旧方法。(事实上​​,我们刚刚在源代码目录中的__init__.py文件中导入了辅助模块。 )当用户脚本以旧方式导入辅助模块时,ourpackage我们非常希望发出警告(使用标准库)。warnings

所以我的问题是:有没有办法判断用户是否以“错误”的方式导入了帮助模块?理想情况下,我们希望在不检查用户代码的情况下实现这一点。

4

1 回答 1

1

It depends on how you are achieving the "still provide the old way". It sounds like you are leaving the old modules directly on the search path and just doing import helpermodule inside ourpackage. (That is, you yourself are still importing the module in the "wrong" way.) In that case here is one possibility.

\dir_on_path
helper.py
    \ourpackage
        __init__.py

#### helper.py
import sys
if 'testpack' in sys.modules:
    print "Imported the good way"
else:
    print "Imported the bad way"
####

#### __init__.py
import teststuff
####

However, note that this way of doing it leaves some awkward problems. You will not be able to do import testpack.teststuff. Also, there remains the possibility that the person could import teststuff in both the good and bad ways, creating two separate copies in sys.modules.

If this isn't how you are "still providing the old way" please edit to clarify.

于 2012-05-31T07:42:31.797 回答