Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

后端 未结 2 815
[愿得一人]
[愿得一人] 2020-12-04 10:47

I was recently having a problem with a python ImportError, where the module was found when running on my local computer but not found on the CI server. I solved this problem

2条回答
  •  孤街浪徒
    2020-12-04 11:17

    I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

    1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
    * append(item) add item to the end of the list,
    * insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

    2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
    * If you have no file name collisions, the order of the path has no impact,
    * If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

    But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

提交回复
热议问题