多级相对导入 [英] Multilevel relative import
本文介绍了多级相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
多级相对导入
我有以下文件夹结构
top\
__init__.py
util\
__init__.py
utiltest.py
foo\
__init__.py
foo.py
bar\
__init__.py
foobar.py
我想从 foobar.py
访问模块 utiltest.py
。我尝试了以下相对导入,但这不起作用:
来自... util.utiltest import *
I want to access from foobar.py
the module utiltest.py
. I tried following relative import, but this doesn't work:
from ...util.utiltest import *
我总是得到
ValueError:尝试相对导入超出toplevel包
怎么做这样一个多方相对导入?
How to do such a multileve relative import?
推荐答案
你必须从中导入 foobar
父文件夹顶部
:
You must import foobar
from the parent folder of top
:
import top.foo.bar.foobar
这告诉Python top
是最高的级别包。只能在包内进行相对导入。
This tells Python that top
is the top level package. Relative imports are possible only inside a package.
这篇关于多级相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文