sys path modification

Cem Karan cfkaran2 at
Mon Jul 27 20:56:07 CEST 2015

On Jul 27, 2015, at 1:24 PM, neubyr <neubyr at> wrote:

> I am trying to understand sys.path working and best practices for managing it within a program or script. Is it fine to modify sys.path using sys.path.insert(0, EXT_MODULES_DIR)? One stackoverflow answer - - suggests that it may break external 3'rd party code as by convention first item of sys.path list, path[0], is the directory containing the script that was used to invoke the Python interpreter. So what are best practices to prepend sys.path in the program itself? Any further elaboration would be helpful. 

Why are you trying to modify sys.path?  I'm not judging, there are many good reasons to do so, but there may be safer ways of getting the effect you want that don't rely on modifying sys.path.  One simple method is to modify PYTHONPATH ( instead.

In order of preference:

1) Append to sys.path.  This will cause you the fewest headaches.

2) If you absolutely have to insert into the list, insert after the first element.  As you noted from SO, and noted in the docs (, the first element of sys.path is the path to the directory of the script itself.  If you modify this, you **will** break third-party code at some point.  

Cem Karan

More information about the Python-list mailing list