Multilevel relative import

后端 未结 2 646
执念已碎
执念已碎 2020-12-31 03:15

Multilevel relative import

I have following folder structure

top\\
   __init__.py
   util\\
      __init__.py
      utiltest.py
   foo\\
      __init         


        
2条回答
  •  遥遥无期
    2020-12-31 03:25

    I realize this is an old question, but I feel the accepted answer likely misses the main issue with the questioner's code. It's not wrong, strictly speaking, but it gives a suggestion that only coincidentally happens to work around the real issue.

    That real issue is that the foobar.py file in top\foo\bar is being run as a script. When a (correct!) relative import is attempted, it fails because the Python interpreter doesn't understand the package structure.

    The best fix for this is to run foobar.py not by filename, but instead to use the -m flag to the interpreter to tell it to run the top.foo.bar.foobar module. This way Python will know the main module it's loading is in a package, and it will know exactly where the relative import is referring.

提交回复
热议问题