0

i want to import file that is in parent folder and i dont want to do this with sys

my files:

import/
   sub_folder/
       x.py
   a.py

file a.py:

def spam():
    print "gg"

file x.py:

from .. import a

def main():
    a.spam()

if __name__ == "__main__":
    main()

this is the error- Attempted relative import in non-package

I tryed all and nothing works

Chad
  • 21
  • 3
  • Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – MyNameIsCaleb May 07 '19 at 18:27
  • Possible duplicate of [How to fix "Attempted relative import in non-package" even with \_\_init\_\_.py](https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py) – l'L'l May 07 '19 at 18:28

1 Answers1

0

Relative imports don't work on files that get executed as the main file.

Relative imports depend on the __name__ attribute - which is set to __main__ if you're executing that file directly.

You need to execute that file as a package

python -m import.sub_folder.x

And you need to put some __init__.py files in the folders to make python recognize them as packages

rdas
  • 20,604
  • 6
  • 33
  • 46