0

I have a pretty simple Python3 project with this folder structure:

➜  (venv:evernote) evernote_bear_project git:(master) ✗ tree 
.
├── README.md
├── bear2evernote
│   ├── static
│   └── templates
├── config
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── sample
│   ├── EDAMTest.py     <--- This here imports from `util.files`
│   └── enlogo.png
└── util
    ├── __init__.py
    ├── files.py
    └── test_files.py

Now I try to import from util.files in sample/EDAMTest.py but I get an error message:

$ cd sample
$ python EDAMTest.py
Traceback (most recent call last):
File "EDAMTest.py", line 18, in <module>
    from ..util.files import *
ValueError: attempted relative import beyond top-level package

The import statement in EDAMTest.py is this line:

from ..util.files import * 

There are many articles about Python imports like this, but I still can't resolve it.

The Definitive Guide to Python import Statements

This SO post did't help either:

How to resolve “ValueError: attempted relative import beyond top-level package”


EDIT: If I run the script from the root folder, then I get the same error:

➜  (venv:evernote) evernote_bear_project git:(master) ✗ python sample/EDAMTest.py
Traceback (most recent call last):
File "sample/EDAMTest.py", line 18, in <module>
    from ..util.files import *
ValueError: attempted relative import beyond top-level package
Ugur
  • 1,914
  • 2
  • 25
  • 46
  • You are running the script from inside the "sample" directory, so relative imports cannot traverse up the directory tree above this directory. What if you stay one directory above the "sample" directory and execute the EDAMTest.py script? – Matt Runion Sep 05 '18 at 19:06
  • Same error. See the EDIT section above – Ugur Sep 05 '18 at 19:09
  • Then you are going to have to do what was suggested in the other SO link -- create a Python script in the root folder of your project and import and execute the EDAMTest.py code there, or modify the path like the SO article mentions. Python 3 will not let you do what you are wanting to do the way you are wanting to do it. – Matt Runion Sep 05 '18 at 19:11
  • Here is an excellent post that explains it [Script vs module](https://stackoverflow.com/a/14132912/5115219) – Ugur Sep 05 '18 at 20:28

0 Answers0