Just after standard pythonmodule imports? If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
I generally do it before importing anything. If you're worried that your module names might conflict with the Python stdlib names, then change your module names!
I often use a shell script to launch my python applications: I put my "sys.path.insert" (append) statement just after the "standard" python module imports in my "launch python script".
Using sys.path.insert(0, ...) gets your "imports" in priority in the path list.
It should go before the import
or from
statements that need it (which as you say is obvious). So for example a module could start with:
import sys
import os
import math
try:
import foo
except ImportError:
if 'foopath' in sys.path: raise
sys.path.append('foopath')
import foo
Note that I've made the append conditional (on the import failing and the specific module's path not being on sys.path
yet) to avoid the risk of sys.path
ending up with dozens of occurrences of string foopath
, which would not be particularly helpful;-).
I think it's a matter of taste. But most people tend to put it behind the import sys
:-)
I prefer wrapping it in an extra function:
def importmod_abs(name):
sys.path.append() ..
__import__ ...
sys.path.pop()
... this way sys.path
remains clean. Of course that's only applicable to certain module structures. Anyways, I'd import everything that works without altering sys.path
first.
One reason this isn't mentioned in PEP 8 or other good Python style guides is that modifying sys.path
isn't something you want to do in a real program; it makes your program less robust and portable. A better solution might be to put your package somewhere that would already be in sys.path
or to define PYTHONPATH
systemwide to include your package.