python - Relative import structure -


my program has structure so:

scripts/      __init__.py      mod1.py      mod2.py      sub1/          __init__.py          mod3.py      sub2/          __init__.py          mod4.py  

all programs started mod1.py chooses subsequent script (mod3/mod4.py) run based off supplied system arguments. top level directory @ import scripts/.

say run program such >mod1.py 3 executes sub1.mod3. within mod3 need function defined in mod2 (this module holds reused code blocks mod3/mod4).

when try from .. import mod2 valueerror attempted relative import beyond top-level directory. referencing docs on syntax, , if compare them situation, mod3.py current module (after mod1.py) called it.

what wrong how trying relative imports?

mod1.py:

import sys  def imp(module):     m = __import__(module) # equivalent import module m     m.start()  if __name__ == '__main__':     mods = {'3': 'sub1.mod3',             '4': 'sub2.mod4'}      imp(mods[sys.argv[1]]) 

mod3.py

from .. import mod2  # fails import mod2  # works; guessing since import considers mod1 location top-level . . . def start():     # stuff 

you say:

all programs started mod1.py chooses subsequent script (mod3/mod4.py) run based off supplied system arguments. top level directory @ import scripts/.

from docs (6.4.2 intra-package referencing):

note relative imports based on name of current module. since name of main module "__main__", modules intended use main module of python application must use absolute imports.

hence must use absolute imports in files.

so code should read

from scripts.mod2 import x 

or

from scripts import mod2 

additionally, i'm not sure why want this. simpler keep both modules in separate packages, , load them if condition, while keeping files in same directory, sans __init__.py:

if sys.argv[1] == '3':     import mod3 elif sys.argv[2] == '4':     import mod4 

if must keep them in separate folders, use strcture:

scripts/     mod1.py     pkg/         __init__.py         mod2.py         sub1/             __init__.py             mod3.py         sub2/             __init__.py             mod4.py 

with structure relative imports should work. importing be:

if sys.argv[1] == '3':     pkg.sub1 import mod3 elif sys.argv[2] == '4':     pkg.sub2 import mod4 

it worthy note that, regardless of part of library or package import, entire package gets imported anyway - it's not available in scope.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -