is this a good way to do imports ?

Stef Mientki stef.mientki at gmail.com
Wed Nov 5 14:14:05 EST 2008


hello,

I can't find any good documentation or examples of packages,
so I'm not sure if this is good / correct way, although it seems to work.

root
  / dir1
    / file1.py
    / general.py
 
  / dir2
    / file2.py

  / general_root.py

Now I want to be able to use functions of file2 in file1,
and vice-versa.
In practice the directory structure is more complex and nested more deeply,
and basically I want all modules to be reachable by all other modules.

==== file1.py ====
import general
import file2
print file2.var

==== file2.py ====
var = 33

==== general.py ====
dir = '../dir'
import sys
if not ( dir in sys.path ) :
  sys.path.append ( dir )

For a more complex directory structure this is not doable.
So another approach could be

==== file1.py ====
import general
import file2
print file2.var

==== file2.py ====
var = 33

==== general.py ==== is doesn't need to know about other branches, only 
of the root
dir = '../'
import sys
if not ( dir in sys.path ) :
  sys.path.append ( dir )
import general_root

==== general_root.py ==== this can be fully automated
dir = '../dir2/'
import sys
if not ( dir in sys.path ) :
  sys.path.append ( dir )

And for the last thought I had:
why not use __init__.py instead of the general.py procedure ??

Maybe I should also set the current working directory to the root or to 
the python file I launch ??

please enlighten me.

thanks,
Stef Mientki




More information about the Python-list mailing list