从 __init__.py 中的子模块导入函数而不暴露子模块
Import function from submodule in __init__.py without exposing submodule
我正在处理一个 Python 项目,其目录结构类似于:
foo/
├── bar
│ ├── bar1.py
│ ├── bar2.py
│ └── __init__.py
└── __init__.py
其中模块 bar1
定义函数 function1
.
我想让我的代码的用户直接从 foo
导入 function1
(而不是其他),即通过 from foo import function1
。很公平,可以通过以下 foo/__init__.py
:
来实现
from .bar.bar1 import function1
__all__ = ['function1']
现在的问题是某人 运行 import foo
在例如当尝试自动完成 foo.
时,REPL 仍将与 foo.bar
一起显示在 foo.function1
旁边。有没有办法在不将其名称更改为 _bar
的情况下从用户那里 "hide" bar
的存在?
我可能会以错误的方式解决这个问题,所以我愿意接受有关如何重构我的代码的建议,但我想避免重命名模块。
您可以通过删除 foo/__init__.py
中的 bar
引用来隐藏它:
from .bar.bar1 import function1
__all__ = ['function1']
del bar
Existence of __all__
affects the from <module> import *
behavior only
我正在处理一个 Python 项目,其目录结构类似于:
foo/
├── bar
│ ├── bar1.py
│ ├── bar2.py
│ └── __init__.py
└── __init__.py
其中模块 bar1
定义函数 function1
.
我想让我的代码的用户直接从 foo
导入 function1
(而不是其他),即通过 from foo import function1
。很公平,可以通过以下 foo/__init__.py
:
from .bar.bar1 import function1
__all__ = ['function1']
现在的问题是某人 运行 import foo
在例如当尝试自动完成 foo.
时,REPL 仍将与 foo.bar
一起显示在 foo.function1
旁边。有没有办法在不将其名称更改为 _bar
的情况下从用户那里 "hide" bar
的存在?
我可能会以错误的方式解决这个问题,所以我愿意接受有关如何重构我的代码的建议,但我想避免重命名模块。
您可以通过删除 foo/__init__.py
中的 bar
引用来隐藏它:
from .bar.bar1 import function1
__all__ = ['function1']
del bar
Existence of __all__
affects the from <module> import *
behavior only