Louis Thibault
Louis Thibault

Reputation: 21390

Permanently altering sys.path ... good idea or no?

I have to append sys.path in order for one of my scripts to work. As I will be doing this often, I was considering permanently adding the path.

Is this generally considered safe?

Also, if my main script appends sys.path, do I need to do so for every module used in that script, or are the changes global?

Thanks!

Upvotes: 4

Views: 7137

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208405

If you find yourself commonly adding elements to sys.path, adding them permanently can be a good idea. However you should not do this by editing sys.path directly, it is best accomplished by setting the PYTHONPATH environment variable.

There is some documentation on how to set PYTHONPATH on Windows, and this article has some good information for setting environment variables on Linux.

Upvotes: 4

Brigand
Brigand

Reputation: 86220

It's usually best to do it at the start of a script. The main reason is portability. If you move the script from one folder to another, or even worse, a different computer... it's not going to work.

The changes are almost always global. The exception is when you import path from sys, instead of importing sys.

# pathprinter.py
import sys
print sys.path

# tester.py
from sys import path
path = ['a', 'completely', 'new', 'value']
import pathprinter
   # Original path printed

Upvotes: 1

Related Questions