[Tutor] Import package module problem

A.T.Hofkamp a.t.hofkamp at tue.nl
Tue May 12 09:14:36 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



More information about the Tutor mailing list