How to fix "A relative import attempt was made from a non-package even though there is __init__.py" error
P粉566048790
2023-08-21 15:15:11
<p>I'm trying to follow PEP 328, using the following directory structure: </p>
<pre class="brush:php;toolbar:false;">pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py</pre>
<p>In <code>core_test.py</code> I have the following import statement</p>
<pre class="brush:php;toolbar:false;">from ..components.core import GameLoopEvents</pre>
<p>However, when I run, I get the following error: </p>
<pre class="brush:php;toolbar:false;">tests$ python core_test.py
Traceback (most recent call last):
File "core_test.py", line 3, in <module>
from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package</pre>
<p>I found "relative path not working even with __init__.py" and "Import a module from a relative path" in my search, but they didn't help. </p>
<p>Is there anything I'm missing here? </p>
To elaborate on Ignacio Vazquez-Abrams’s answer:
Python’s import mechanism is
__name__
relative to the current file. When a file is executed directly, its name is not the usual name, but"__main__"
is used as the name. Therefore, relative imports don't work.As Ignacio suggested, you can execute it using the
-m
option. If part of your package is run as a script, you can also use the__package__
attribute to tell the file what name it should have in the package hierarchy.For more information, please see http://www.python.org/dev/peps/pep-0366/.
Yes. You are not using it as a package.