[Tutor] Import package module problem

mandel at themacaque.com mandel at themacaque.com
Tue May 12 09:42:52 CEST 2009


> mandel at themacaque.com wrote:
>> Hello there,
>>
>> I have just started working with python and I have some issues
>> understanding how I should be importing modules from packages. Curretly
>> I
>> have the following tree structure:
>>
>> general/
>>     __init__.py
>>     address_book.py
>> groups/
>>     __init__.py
>>     contact_group.py
>>
>> where groups and general are in the same level and all the __init__.py
>> files are empty.
>
> You seem to need a common starting point:
>
> %  ls -R
> .:
> general  groups  main.py
>
> ./general:
> gen.py  __init__.py
>
> ./groups:
> grp.py  __init__.py
>
> The same setup as you have, except my names are less nice, and I have a
> ./main.py added
>
> The latter file is the starting point:
>
> %  cat main.py
> from general import gen
>
> The general/gen file imports the groups/grp file, and then prints some
> text:
>
> %  cat general/gen.py
> from groups import grp
> print "inside gen.py"
>
> Finally, the groups/grp.py file outputs only some text:
>
> %  cat groups/grp.py
> print "inside grp.py"
>
> When I run this code, I get the following output:
>
> %  python main.py
> inside grp.py
> inside gen.py
>
>
> By starting from main.py, the Python interpreter uses the current "."
> directory as starting point for imports. That starting point is then used
> to
> refer to other files (possibly in another package).
>
>
> Sincerely,
> Albert
>
>

I have actually rearranged my code to have such hierarchy which obviously
works. The problem is that I want ot be able to perform unit tests withinn
 the package of the code. I keep having the problem with

from ..groups.contact_group import ContactGroup

I have read that the notation is correct, but how do you get it too work?
I can alway move all the tests one level up, but I really would prefer not
to have to do it.

Kr,

Manuel



More information about the Tutor mailing list