开发者

Where should sys.path.append('...') statement go?

开发者 https://www.devze.com 2022-12-20 23:04 出处:网络
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 mentio

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 f开发者_StackOverflow社区or it.


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;-).


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.


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.


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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号