Python – How to fix “Attempted relative import in non-package” even with


I'm trying to follow PEP 328, with the following directory structure:


In I have the following import statement

from ..components.core import GameLoopEvents

However, when I run, I get the following error:

tests$ python 
Traceback (most recent call last):
  File "", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

Searching around I found "relative path not working even with" and "Import a module from a relative path" but they didn't help.

Is there anything I'm missing here?

Best Solution

To elaborate on Ignacio Vazquez-Abrams's answer:

The Python import mechanism works relative to the __name__ of the current file. When you execute a file directly, it doesn't have its usual name, but has "__main__" as its name instead. So relative imports don't work.

You can, as Igancio suggested, execute it using the -m option. If you have a part of your package that is meant to be run as a script, you can also use the __package__ attribute to tell that file what name it's supposed to have in the package hierarchy.

See for details.