缩短python中的命名空间

时间:2012-06-21 16:41:34

标签: python python-2.7

我想缩短我的命名空间 sandbox.auto.tools sandbox.tools 。我如何实现(自动冗余)?我查看了其他消息,但没有找到类似于我正在寻找的东西。以下是我的目录结构。

sandbox\auto\tools\foo.py (contains a function display() as described below)
    def display():
        print "hello"

sandbox\test\bar.py 
    import sandbox.auto.tools as sandbox.tools (Error)

我知道我可以做到以下几点。

  sandboox\test\bar.py 
    from sandbox.auto.tools import foo as tools
    tools.display()

有任何建议/指示吗?

4 个答案:

答案 0 :(得分:3)

允许您指定的确切语法(使用sandbox.tools而不是sandbox_tools)将需要在导入之前或之后更改模块。

便宜的方式:

import sandbox.auto.tools
sandbox.tools = sandbox.auto.tools

永久方式(需要修改模块源的能力):

在来源中创建或更改sandbox/__init__.py说:

import auto.tools as tools
__all__ = ['tools', ...]

答案 1 :(得分:0)

如果您确实希望sandbox.tools可用,请将其添加到sandbox/__init__.py

from .auto import tools

这会将tools添加到sandbox包的命名空间中,您将能够执行此操作:

from sandbox import tools
tools.dispaly()

或者,你要求的是什么,这是:

import sandbox
sandbox.tools.display()

答案 2 :(得分:0)

我终于找到了一个有你的建议/帮助的解决方案。但是,我仍然不满意。

沙箱/的初始化的.py

import auto.tools as tools
__all__ = ['tools']

import sandbox.auto.tools.foo
sandbox.tools.foo = sandbox.auto.tools.foo

sandbox / test / bar.py - 这似乎有用

import sandbox
print dir(sandbox)
foo = sandbox.tools.foo
foo.display()

但是 - 我不能再这样说了

from sandbox.tools import foo
or
from sandbox.tools import foo as tools2

看起来我能够处理引用,但我仍然不完全理解python中命名空间的概念。

答案 3 :(得分:0)

我的一位同事指出,我们可以将以下行添加到sandbox / init .py,它应该解决此特定问题。

<强>路径 .append( '沙盒/自动')