Same sub-folder names for python imports -


  • i'm working on collection of python scripts daily work.
  • to avoid duplication, want make use of import share tools.
  • to keep repository maintainable, have sub-folders collect scripts specific purposes , lib-folder in each sub-folder keep shared functions.

the structure looks this.

root ├── lib │   ├── hello.py └── sub     ├── hello_user.py     └── lib  __init__.py files exist, filtered better readability 

the code in hello_user.py this:

from lib.hello import hello hello() 

and in hello.py:

def hello():     print("hello") 
  • pythonpath set root folder.
  • when try execute "python sub/hello_user.py", error "importerror: no module named hello". if rename sub/lib sub/lib_hide, expected output "hello".
  • how python import root/lib instead of root/sub/lib?
  • setting pythonpath "root/.." , importing "root.lib" work not viable option (would require changes in setups using scripts , in existing scripts).
  • i'd prefer solution modify import statement. relative path fine, how name relative path parent folder? "..".lib.hello not work.

if execute script using python sub/hello_user.py, directory sub automatically added sys.path first element. therefore root/sub/lib found before root/lib , therefore hide it, no matter pythonpath points. way change make sure root appears before root/sub in path:

sys.path.insert(0, '.../root') 

if import module (or execute module directly using python -m sub.hello_user) situation different.

in python2, import implicitly regarded relative, try import root/sub/lib/hello.py, root/lib again shadowed root/sub/lib.

python3 fixes making imports absolute default, import root/lib/hello.py. can behaviour in python2 adding from __future__ import absolute_import:

# root/sub/hello_user.py:  __future__ import absolute_import lib import hello      # imports root/lib/hello.py sub.lib import hello  # imports root/sub/lib/hello.py .lib import hello     # same, relative import instead of absolute 

however still work if sub isn't in path earlier root.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -