I am in the file "Query.py" trying to import the class SqlQuery from the file "database.py" which is located up two levels & then down one in another directory (also called "database"). Then the import statement I expect to work looks like this: from ...database.database import SqlQuery
But that gives me:
Traceback (most recent call last):
File "C:/Users/Roland/dir1/2020/Indeed-Scraper/scraper/classes/Query.py", line 16, in <module>
from ....database.database import SqlQuery
ValueError: attempted relative import beyond top-level package
since I understand way you run the file can be important, I am trying to run Query.py using my PyCharm IDE
This is way harder than I expected it to be!
Here are the relevant parts of my file structure:
project_name/
__init__.py
database/
__init__.py
database.py
scraper/
__init__.py
classes/
__init__.py
Query.py
And here are the various things I've tried: (this code sits at the top of Query.py, one line above the from ...database.database import SqlQuery
statement)
import sys
sys.path.append(os.path.realpath('...')) # attempt 1
sys.path.insert(0, '') # attempt 2
sys.path.append("...") # attempt 3 - I think it is strange that adding "..." to the path did not work?
I did Google & check out various StackOverflow threads about this. I either didn't find a satisfactory answer (I can't believe I need to write sys.path.append(anything)
in the best solution) or I didn't understand a solution when I found it. I've been here, here, here, to this link, and here, among other places.
I'm also reading the top-level answer in the popular post, "Relative imports for the billionth time" and I understand that:
- My Query.py file is exectued as a "top-level script" when I execute it directly in my PyCharm IDE.
- "database.py" is loaded as a module since it comes from an import statement.
- "Scripts can't import relative", the author says. "Relative imports are only for use within module files."
...and so, while the thread was informative, I just don't see any answers that seem to be solutions to my problem. I really don't want to post this since it must be a duplicate of some kind, but I haven't found an answer. What gives, Python? Why is importing so hard?
Footnote: Currently the __init__.py
files are empty. Should I be filling them with something to make relative imports easier?