search

Home  >  Q&A  >  body text

How to fix "A relative import attempt was made from a non-package even though there is __init__.py" error

<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>
P粉566048790P粉566048790450 days ago480

reply all(2)I'll reply

  • P粉827121558

    P粉8271215582023-08-22 14:11:27

    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/.

    reply
    0
  • P粉604507867

    P粉6045078672023-08-22 09:39:36

    Yes. You are not using it as a package.

    python -m pkg.tests.core_test

    reply
    0
  • Cancelreply