Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python : imported packages with 'nested' modules

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 ?

like image 793
andio Avatar asked Apr 11 '16 12:04

andio


1 Answers

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
like image 97
aluriak Avatar answered Oct 17 '22 05:10

aluriak