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 ?
1 Answer 1
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
3 Comments
intl which contains a file (scanner.py), and wanted to turn it into a package. In the main file, doing import intl and scanner = intl.Scanner() didn't work. I had to modify __init__.py and add from .scanner import Scanner in it... So, a use case for using a function and a class from packages/subpackages would improve this answer, because it doesn't mention anything about modifying the __init__.py. While I managed to get my script to work, I don't know if I took the right approach :)