[英]Import function from submodule in __init__.py without exposing submodule
I' working on a Python project with a directory structure similar to this: 我正在一个Python项目中,其目录结构类似于以下内容:
foo/
├── bar
│ ├── bar1.py
│ ├── bar2.py
│ └── __init__.py
└── __init__.py
Where the module bar1
defines the function function1
. 其中模块
bar1
定义功能function1
。
I would like to have users of my code import function1
(and nothing else) directly from foo
, ie via from foo import function1
. 我想让我的代码的用户直接从
foo
,即通过from foo import function1
导入function1
(以及其他from foo import function1
。 Fair enough, that can be achieved with the following foo/__init__.py
: 足够公平,可以使用以下
foo/__init__.py
:
from .bar.bar1 import function1
__all__ = ['function1']
The problem now is that someone running import foo
in eg the REPL will still be presented with foo.bar
alongside foo.function1
when trying to autocomplete foo.
现在的问题是,在尝试自动完成
foo.
在REPL中运行import foo
仍会在foo.bar
旁边显示foo.bar
和foo.function1
foo.
. 。 Is there a way to "hide" the existence of
bar
from users without changing its name to _bar
? 有没有办法将用户隐藏
bar
的存在而无需将其名称更改为_bar
?
I might be going about this the wrong way alltogether so I'm open to suggestions on how to restructure my code but I would like to avoid renaming modules. 我可能会一起使用这种错误的方式,所以我愿意就如何重组代码提出建议,但我想避免重命名模块。
You can hide it with deleting bar
reference in foo/__init__.py
: 您可以通过删除
foo/__init__.py
bar
引用来隐藏它:
from .bar.bar1 import function1
__all__ = ['function1']
del bar
Existence of __all__
affects the from <module> import *
behavior only __all__
存在仅影响from <module> import *
行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.