[英]If a Python package is just a module, can that module import from sister modules and expose their functions?
Suppose I have a package structured like: 假设我有一个结构如下的包:
root
+-- package_as_a_module.py
+-- setup.py
+-- requirements.py
In my case, package_as_a_module.py
has grown much larger than initially anticipated, and it's becoming difficult to manage. 以我package_as_a_module.py
, package_as_a_module.py
增长比最初预期的要大得多,并且变得越来越难以管理。 Is it possible to add a new module to the root directory, say utils.py
: 是否可以在根目录中添加一个新模块,例如utils.py
:
# utils.py
def func_a()
return "Hi!"
and then expose the functions of utils.py
via an import statement into package_as_a_module.py
like: 然后通过导入到package_as_a_module.py
的import语句公开utils.py
的功能,例如:
# package_as_a_module.py
from utils import func_a
So that after installation, I can use from package_as_a_module import func_a
? 这样在安装后,我可以使用from package_as_a_module import func_a
来使用?
I attempted this without success, here . 我在这里尝试未成功。 The modules from which the main module imports are not recognized, and the import fails. 无法识别从中导入主模块的模块,并且导入失败。 I suspect this might be possible with a true package structure, maybe in the init .py file or something. 我怀疑使用真正的包结构可能会发生这种情况,可能在init .py文件中或其他内容中。 I'll give that a whirl next. 接下来,我会旋转一下。
If no one proposes an alternative, I'll answer my own question in the negative. 如果没有人提出替代方案,我将否定回答我自己的问题。
You can. 您可以。
In your file main_module.py
you did not call the print_all()
function, that is why nothing happened. 在文件main_module.py
您没有调用print_all()
函数,这就是为什么什么也没发生的原因。
from module_a import print_hello_world as phw_a
from module_a import print_hello as ph
from module_b import print_hello_world as phw_b
def print_all():
ph()
phw_a()
phw_b()
print_all() # You need to call a function for it to do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.