2

I have an installed python library but I want to load it from another folder without altering my installed libraries. Using the following code, I tried to replace the path to it, but now two paths are stored to load the library and the first priority is the older one. How can I set the priority to the new one (or remove the older one)?

import pkg_resources
pkg_resources.declare_namespace('google')
pkg_resources.fixup_namespace_packages(_MY_LIBRARY_DIR)
import google.protobuf
print(google.protobuf.__path__)

Output: ['old path', 'new path']

  • Python will first look for a package in the directory of the current running program, then for a module in the same directory and then it will follow the environment variable [PYTHONPATH](http://stackoverflow.com/questions/19917492/how-to-use-pythonpath). Packages like virtualenv or pyenv will automate manipulation of PYTHONPATH in order to allow coexistence of several versions of the same package in the same system. – Paulo Scardine Apr 13 '17 at 14:01
  • 1
    BTW this looks like a classic example of the X/Y problem. Instead of asking about your problem X (how to have conflicting versions of the same package in one system), you are asking about your devised solution Y (fiddle with the import path for Python modules). – Paulo Scardine Apr 13 '17 at 14:08

2 Answers2

0

Although you can use __file__ to find the path of modules and libraries,

print(google.protobuf.__file__)

but what you want to accomplish is a classic case for a virtual environment.

Virtual Environments are tools to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them.

Virtualenv

Pyenv

hspandher
  • 15,934
  • 2
  • 32
  • 45
0

Use Virtualenv.

From the Hitchhikers Guide to Python:

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

Anurag Saxena
  • 388
  • 2
  • 7