在python中缩短名称空间

在python中缩短名称空间,python,python-2.7,Python,Python 2.7,我想从say中缩短名称空间 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 impor

我想从say中缩短名称空间 sandbox.auto.toolssandbox.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()

有任何建议/指针吗?

如果您真的想使用
沙盒工具
,请将其添加到
沙盒/\uuuuuuu init\uuuuuuuuuupy

from .auto import tools
这会将
tools
添加到
sandbox
包的命名空间中,您将能够执行以下操作:

from sandbox import tools
tools.dispaly()
或者,你要的是什么,这是:

import sandbox
sandbox.tools.display()

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

便宜的方法:

import sandbox.auto.tools
sandbox.tools = sandbox.auto.tools
永久方式(需要能够修改模块源):

在源代码中创建或更改沙盒/\uuuuu init\uuuuu.py,表示:

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

在你的建议/帮助下,我终于找到了解决办法。但是,我还是不满意

沙盒/初始化.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中名称空间的概念。

我的一位同事指出,我们可以在sandbox/init.py中添加以下行,它应该可以解决这个特定问题


path.append('sandbox/auto')

将sandbox.auto导入为sandbox
?我尝试过,但没有解决问题。然后我需要定义下面的语句-“from sandbox.tools import foo”,它给了我一个错误,告诉我没有名为tools.display的模块被定义为foo.py。上面的代码仍然不适用于我。我收到错误“ImportError:No module named tools”(导入错误):您的
auto
tools
子模块可能还需要一个
\uuuu init\uuuuuuuuuy.py
。我收到一个导入错误。为了清晰起见,没有名为tools的模块:这是指,因此您还必须导入
sys