Inside packagetest/
, I have these four files:
__init__.py
:
class TestError(Exception): pass
__main__.py
:
from . import TestError from .abc import defgh from .ijk.lmn import opq
abc/__init__.py
:
def defgh(): pass
ijk/lmn.py
:
def opq(): pass
When running __main__.py
, I get this error:
File "D:\\packagetest_ main _.py", line 1, in
from . import TestError
ImportError: attempted relative import with no known parent package
Why does from . import TestError
from . import TestError
generate an error here?
How to solve this problem here and modify the code as little as possible?
I've already read Relative imports in Python 3 but I don't see how to modify my code here to make it work.
The article ImportError: attempted relative import with no known parent package provides several solutions to this problem and explain how relative import works.
One solution that works for me is to move everything in a parent directory parent/
:
parent/
|- test.py
|- packagetest/
|- __init__.py
|- __main__.py
|- abc/
|- __init__.py
|- ijk/
|- lmn.py
Then import the package inside parent/test.py
:
import packagetest
and then it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.