Transient import path


#1

Another interesting tidbit that appeared in the chat; how can you, given (1) a directory of modules where some modules conflict with other modules on your PYTHONPATH, where (2) you are interested in one that isn’t in conflict?

Example

Here is the contents of existing PYTHONPATH

pythonpath/
  PySide
  requests

And you would like tractor from here.

tractor/site-packages/
  PySide
  tractor

As you can see, another copy of PySide resides in there, one that would not work as a replacement for the one you already have - perhaps it is a different version, perhaps compiled in some other way.

Workaround #1

In one-off situations, a quick and dirty way around it is this.

import sys
sys.path.insert(0, "/tractor/site-packages")
import tractor
sys.path.pop(0)

Given Python’s caching mechanism, this can happen anywhere in your active Python session, and other modules attempting to import it will automatically reference the already imported copy of tractor, even though it is no longer on your sys.path.

other_module.py

import tractor
# ok

See the sys.modules dictionary for where Python is searching before looking in sys.path.

Workaround #2

If the problem is recurring or permanent, a more sustainable option may be to rethink your strategy. Rather than maintain these two directory structures of conflicting packages, you could split them up.

packages/
  PySide_1.21/
    PySide
  PySide_1.32/
    PySide

Then you are free to add the versions you are interested in.

$ cd packages
$ export PYTHONPATH=$(pwd)/PySide_1.21:$PYTHONPATH

Due to the more explicit PYTHONPATH, dedicated tools were built to manage these.

Tools such as…

Enjoy!