By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,526 Members | 1,618 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,526 IT Pros & Developers. It's quick & easy.

is this a good way to do imports ?

P: n/a
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

Nov 5 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Nov 5, 2:14*pm, Stef Mientki <stef.mien...@gmail.comwrote:
Now I want to be able to use functions of file2 in file1,
and vice-versa.
It sounds like __all__ in __init__.py would work:
http://www.python.org/doc/2.5.2/tut/...00000000000000

If not, then pkgutil might of use?
http://docs.python.org/library/pkgutil.html
Nov 5 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.