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 by swapping sys.path.append(path)
in my script with sys.path.insert(0, path)
where path
is the string module location.
Since this is my module and not an installed package (related question), why does the order of paths fix this problem?
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
andappend
methods are not specific tosys.path
and as in other languages they add an item into a list or array and :*
append(item)
additem
to the end of the list,*
insert(n, item)
inserts theitem
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 notinsert
to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.Because python checks in the directories in sequential order starting at the first directory in
sys.path
list, till it find the.py
file it was looking for.Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
So, most probably, you had a
.py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).Also, a thing to note about
ImportError
s , lets say the import error says -ImportError: No module named main
- it doesn't mean themain.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.Example -
My directory structure looks like -
Now From
testmain.py
, I callfrom shared import phtest
, it works fine.Now lets say I introduce a shared.py in
test
directory` , example -Now when I try to do
from shared import phtest
fromtestmain.py
, I will get the error -As you can see above, the file that is causing the issue is
shared.py
, notphtest.py
.