I have the following package structure:
.
└── package
├── __init__.py
├── sub_package_1
│ ├── __init__.py
│ └── main_module.py
├── sub_package_2
│ ├── __init__.py
│ └── some_module.py
└── sub_package_3
├── __init__.py
└── some_module.py
In package/sub_package_1/main_module.py
I want to use both package/sub_package_2/some_module.py
and package/sub_package_3/some_module.py
. For this I want to use intra-package reference . I know that I can use from ..sub_package_1 import some-module
but because of the similar name I want to use dotted syntax such as sub_package_1.some_module
.
Using from .. import sub_package_2
I obviously cannot access sub_package_2.some_module
because sub_package_2
is a package. However I found out that using
from .. import sub_package_2
from ..sub_package_2 import some_module
I can access sub_package_2.some_module
. Apparently the 2nd import adds some_module
to sub_package_2
(checking dir(sub_package_2)
).
My questions are:
import package
followed by from package import module
add module
to package
? What is Python actually doing here? 1.
In the file __init__.py
of sub_package_2 you write
from . import some_module
And in main_module.py
you can must write
from .. import sub_package_2
And the code sub_package_2.some_module
should work now
2.
"How import in python work" you can read more here Importing Python Modules
from .. import sub_package_2
creates a reference to sub_package_2
in the current namespace. Package sub_package_2
is like a module now and is defined in the file __init__.py
. If you wrote nothing in __init__.py
, sub_package_2 won't know some_modue
from ..sub_package_2 import some_module
create a reference to the module some_module
of the package sub_package_2
with the name some_module . It's something like some_module = sub_package_2.some_module
. You see: there are a reference to some_module
in sub_package_2
too. And now sub_package_2
knows the module some_module
Important: You can use sub_package_2.some_module
but only some_module
will work too. They are identical after your 2 imports.
And if you write in the __init__.py
:
from . import some_module
some_module
belongs to sub_package_2
automatically
For similar module names you can use as
from ..sub_package_1 import some_module as some_module_1
from ..sub_package_2 import some_module as some_module_2
from ..sub_package_3 import some_module as some_module_3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.