When i import modules , this nested scenario works fine. But when i try to import packages , i got inconsistent result. Here's the very simple case :
contents of my current folder :
mypackages <directory>
__init__.py
one.py
two.py
three.py
this is the script :
__init__.py :
import one
one.py :
import two
two.py :
import three
I'm expecting that i should be able to access two and three this way :
import mypackages
mypackages.one.two
mypackages.one.two.three
or in other word the logical level shoul be like this :
one
two
three
But when i do import mypackages, i got all the modules exposed at the same level :
>>> import mypackages
>>> print dir(mypackages)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'__path__', 'one', 'three', 'two']
It should only show one
module , right ?
I'm confused why it shows all one , two
and three
which means they are at the same level ( i can use mypackages.two and mypackages.three directly ).
Does anyone have any explaination ?
You should read this.
By putting the files at the same level, you put them is the same package level. In your case, you need to get this architecture:
mypackage
├── __init__.py
├── one.py # contains "import two"
└── two
├── __init__.py
├── two.py # contains "import three"
└── three
├── __init__.py
└── three.py
And then, you can access the package with:
import mypackage.one
import mypackage.one.two
import mypackage.one.two.three
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With