Christopher Dorian
Christopher Dorian

Reputation: 2243

Python: Is it possible to only have specific modules from a folder in your sys.path

There are only one or two modules which I need from the a folder which contains several other python modules. When I add the folder to my path, I effectively make all the modules in that folder available to me. But there are several outdated modules which I do not want. Is it possible to only make a certain subset of those modules available to me?

Upvotes: 1

Views: 145

Answers (3)

alexis
alexis

Reputation: 50200

Create a new directory. For each module you want to import, add a symbolic link (ln -s) pointing to the real module. Then add the new directory to your path, and you won't have to play games with your include order.

mkdir ./mymods
export PYTHONPATH="$PYTHONPATH":`pwd`/mymods 
cd mymods
ln -s ../allmods/module1.py 
ln -s ../allmods/module2.py

Upvotes: 1

Abhijit
Abhijit

Reputation: 63737

Reading your question I understand that

  1. You are including the folder in your pythonpath because you need couple of modules from it.
  2. As it contains some other modules which may be outdated compared to the version you are using, you do not want to end up importing the wrong library.

I would suggest two options which might work for you.

  1. Ensure that this folder you are including is at the end of sys.path. This would ensure that any modules that you are already importing if present in the newly included folder is never imported from that particular location.
  2. (Only for *nix) Create another folder, and create a symlink to the files you are interested in. You should then include that other folder that you created.

Reading your comment, I would suggest, the best option would be to add the following lines somewhere in your script but before you import`

import sys
sys.path.append('/whatever')

Upvotes: 2

miku
miku

Reputation: 188054

If you

import X

you only import the module X. Nothing else. Something being on your python path is not equivalent to being automatically imported (it's just importable). See also:

Upvotes: 1

Related Questions