简体   繁体   English

How can we go to package inside package when outer package is imported in python

[英]How can we go to package inside package when outer package is imported in python

Can anyone help me with a question, if a python package is imported can we directly import package inside another package in package? Can anyone help me with a question, if a python package is imported can we directly import package inside another package in package?

Lets say a python pkg structure is like:假设 python pkg 结构如下:

   module
   |__ module1
   |   |__ __init__.py
   |   |__ pyScript1.py
   |   |__ pyScript2.py
   |__ __init__.py

Then is a python script if we have a script like import module Can we call the pyScript1 using module.pyScript1 without importing module1?然后是 python 脚本,如果我们有一个像import module这样的脚本 我们可以使用module.pyScript1调用 pyScript1 而不导入 module1 吗?

I know this will work by adding all in module > init .py file and add the module1 sub packages in it.我知道这可以通过在 module > init .py 文件中添加所有内容并在其中添加 module1 子包来实现。 but when I run dir(module) I can see module1 in the list.但是当我运行dir(module)时,我可以在列表中看到 module1。 But I don't want to see module1 in dir list.但我不想在目录列表中看到 module1。

Can anyone help with this?有人能帮忙吗?

EDIT:编辑:

What if instead of 'module1' if we have multiple version modules in 'module' like '1_0_0, 1_1_0, 2_0_0,...etc' and we maintain and environmental variable MODULE_VERSION=1.1.0 and according to the version specified we need to refer to that particular version module.如果我们在“模块”中有多个版本模块(例如“1_0_0、1_1_0、2_0_0、...等”)而不是“模块1”,并且我们维护环境变量MODULE_VERSION=1.1.0并根据指定的版本,我们需要参考那个特定的版本模块。

Then is a python script if we have a script like import module Can we call the pyScript1 using module.pyScript1 without importing module1 ?然后是 python 脚本,如果我们有一个像import module这样的脚本我们可以使用module.pyScript1调用pyScript1而不importing module1吗?

The answer, is dependent what you have declared to be initialized in the package __init__.py .答案dependent您在 package __init__.py中声明要初始化的内容。 if you import the pyScript1.py in the __init__.py then the answer yes and if no then the answer is no .如果您在__init__.py中导入pyScript1.py ,那么答案yes ,如果不是,那么答案是no

dunder all __all__ : dunder all __all__

dunder all is good tool for controlling what to export from our module when we got imported (our module not the package). dunder all 是一个很好的工具,可以在我们导入时控制从我们的模块中导出什么(我们的模块不是包)。

inside module/__init__.py file write内部module/__init__.py文件写入

from  .module1 import pyScript1 
__all__ =['pyScript1']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM