【发布时间】:2019-10-20 12:14:48
【问题描述】:
我有一个这样的文件夹结构,每次我尝试使用相对导入时,都会引发错误
├── graphics
│ ├── __init__.py
│ ├── A
│ │ ├── __init__.py
│ │ ├── grok.py
│ │ └── spam.py
└── B
├── __init__.py
└── bar.py
spam.py/
def func():
pass
bar.py/
def f():
pass
所有这些代码都在 grok.py 中测试:
from . import spam
# ImportError: cannot import name 'spam'
from .spam import func
# ModuleNotFoundError: No module named '__main__.spam'; '__main__'
is not a package
from ..B import bar
# ValueError: attempted relative import beyond top-level package
以下代码均不会导致任何错误:
from graphics.A import spam
from graphics.A.spam import func
from graphics.B import bar
from graphics.B.bar import f
【问题讨论】:
标签: python python-3.6 python-import