Safest manner to extend search path for modules?

J

Joseph Turian

Hi,

What is the safest manner to extend search path for modules, minimizing
the likelihood of shooting oneself in the foot?

The system (which includes scripts and their shared modules) may be
checked out in several different locations, but a script in a
particular checked-out version of the system should only use modules
from that checkout location.

e.g. if the system contains a directory scripts/foo/ where all the
scripts are housed, and scripts/modules/ where all the modules are
housed, then is it correct for each script in scripts/foo/ to begin
with:
import sys, os.path
sys.path.append(os.path.join(sys.path[0], "../modules"))

If so, is there a cleaner way of doing this than including the above
text in all scripts?

Thanks,

Joseph
 
M

Mike Meyer

Joseph Turian said:
Hi,

What is the safest manner to extend search path for modules, minimizing
the likelihood of shooting oneself in the foot?

The system (which includes scripts and their shared modules) may be
checked out in several different locations, but a script in a
particular checked-out version of the system should only use modules
from that checkout location.

e.g. if the system contains a directory scripts/foo/ where all the
scripts are housed, and scripts/modules/ where all the modules are
housed, then is it correct for each script in scripts/foo/ to begin
with:
import sys, os.path
sys.path.append(os.path.join(sys.path[0], "../modules"))

If so, is there a cleaner way of doing this than including the above
text in all scripts?

Put that text in a module that is already on the path, and then import
that module.

Or mabye generalize it into a function:

import sys, os.path

def fixpath(*new):
sys.path.extend(os.path.join(sys.path[0], x) for x in new)

This requires 2.4. Change it to ([os.path ... new]) for earlier versions.

Of course, I note that sys.path[0] is '', so the join doesn't do anything.

<mike
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top