How to make the level of subpackage up when import subpackge in main script?

31 Views Asked by At

I want to make a subpackage level up to write the main script in a more simple path. That is, I want to write the path for sub2 in directly pack.sub2 rather than pack.sub1.sub2. Now I made a directory structure and some modules as follows.

pack/sub1/sub2/mod.py

pack/init.py

from .sub1 import sub2

In Ipython,

import pack
dir(pack)
import pack.sub1
import pack.sub2

Error message:

"No module name 'pack.sub2'

dir(pack) shows 'sub1', 'sub2' but import pack.sub2 fails while import pack.sub1 is working naturally. In an other context such as the relation between subpackages inside a library, it might work. But in this case, it is not working. What is the working principle of python in this respect? And how to make the python main script written in a short path form importing subpackage?

1

There are 1 best solutions below

1
Arunbh Yashaswi On
pack/
|-- __init__.py
|-- sub1/
    |-- sub2/
        |-- __init__.py  
        |-- mod.py

I understand that this the structure. Place

from .sub1 import sub2

inside sub2's init.py

this will enable you to import sub2 directly from outside package using

import pack.sub2

Other way is using sys, but that can create thousands of other issue