Edit: based on a Ulf Rompe's comment, it is important you use "1" instead of "0", otherwise you will break sys.path.
I have been doing python for quite a while now (over a year), and I am always confused as to why people recommend you use sys.path.append()
instead of sys.path.insert()
. Let me demonstrate.
Let's say I am working on a module named PyWorkbooks (that is installed on my computer), but I am simultaneously working on a different module (let's say PyJob) that incorporates PyWorkbooks. As I'm working on PyJob I find errors in PyWorkbooks that I am correcting, so I would like to import a development version.
There are multiple ways to work on both (I could put my PyWorkbooks project inside of PyJob, for instance), but sometimes I will still need to play with the path. However, I cannot simply do a sys.path.append()
to the folder where PyWorkbooks is at. Why? Because python will find my installed PyWorkbooks first!
This is why you have to do a sys.path.insert(1, path_to_dev_pyworkbooks)
In summary:
sys.path.append(path_to_dev_pyworkbooks)
import PyWorkbooks # does NOT import dev pyworkbooks, imports installed one
or:
sys.path.insert(1, path_to_dev_pyworkbooks) # based on comments you should use **1 not 0**
import PyWorkbooks # imports correct file
This has caused a few hangups for me in the past, and I would really like it if we (as a community) started recommending sys.path.insert(1, path)
, as if you are manually inserting a path I think it is safe to say that that is the path you want to use!
Or do I have something wrong? It's a question that sometimes bothers me and I wanted it in the open!
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
That's why people consider
insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
This could be important since 3rd party code may rely on sys.path documentation conformance:
you are confusing the concept of appending and prepending. the following code is prepending:
it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through.
sys.path.append()
puts things at the very end of the search sequence.it is advisable that you use something like
virtualenv
instead of manually coding your package directories into thePYTHONPATH
everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:python ecosystems introduction
bootstrapping python virtual environments
if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/