9

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 ?

asked Apr 11, 2016 at 12:01

1 Answer 1

14

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
akinuri
12.3k10 gold badges75 silver badges108 bronze badges
answered Apr 11, 2016 at 12:16
Sign up to request clarification or add additional context in comments.

3 Comments

Care to expand this to cover the usage of functions and classes from the subpackages?
You mean, how to access members of the module objects ?
Yes. I tried the suggested solution, but couldn't make it work. In a dir, I have a folder 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 :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.