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


i having problem python importerror, module found when running on local computer not found on ci server. solved problem swapping sys.path.append(path) in script sys.path.insert(0, path) path string module location.

since module , not installed package (related question), why order of paths fix problem?

because python checks in directories in sequential order starting @ first directory in sys.path list, till find .py file looking for.

ideally, current directory or directory of script first first element in list, unless modify it, did. documentation -

as initialized upon program startup, first item of list, path[0], directory containing script used invoke python interpreter. if script directory not available (e.g. if interpreter invoked interactively or if script read standard input), path[0] empty string, directs python search modules in current directory first. notice script directory inserted before entries inserted result of pythonpath.

so, probably, had .py file same name module trying import from, in current directory (where script being run from).

also, thing note importerrors , lets import error says - importerror: no module named main - doesn't mean main.py overwritten, no if overwritten not having issues trying read it. module above got overwritten .py or other file.

example -

my directory structure looks -

 - test     - shared          - __init__.py          - phtest.py   - testmain.py 

now testmain.py , call from shared import phtest , works fine.

now lets introduce shared.py in test directory` , example -

 - test     - shared          - __init__.py          - phtest.py   - testmain.py    - shared.py 

now when try from shared import phtest testmain.py , error -

importerror: cannot import name 'phtest' 

as can see above, file causing issue shared.py , not phtest.py .


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -