is this a good way to do imports ?

S

Stef Mientki

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top