0

So here is my problem. I have a personal project on Python that I was usually running on PyCharm that I preferred to then switch to VSCode. But now, I have errors on file imports that I don't understand. I don't remember having modified something around the imports, I don't exactly know if it's something to do with the IDE or if it's a global problem.

So basically on the root of my project file, I have a "utils.py" file that I made to store functions I thought I would need to use frequently over my project. At the same location (project root), there's the main .py file that I launch.

I added the path of the utils.py file to my PYTHONPATH environment variables and when I search in the variable sys.path on my Python IDLE, it does actually show me my project root path.

My main.py also manages to correctly get that import.

However, on the project root, I have a folder with Python subfiles in it which cannot access that file. So like, there's at the root main.py, utils.py and folder/subfile.py

On both main.py and the subfile.py, I added "from utils import *" to add the utils import that is recognised On the main.py, the line doesn't show any error On the subfile.py (in the folder), the line has the error "Unable to import 'utils' pylint(import-error)"

TLDR:

  • I have my project root folder with utils.py, main.py, folder/subfile.py
  • utils.py is on my PYTHONPATH environment variable
  • the utils.py import works on main.py
  • the utils.py import doesn't work on the subfile.py in the subfolder
  • (I don't know if it is due to the IDE or not)
lino49
  • 1
  • Maybe you can try to make `utils.py` a whole module so you can import into the `subfile.py`, and other modules in the future. Not really a solution, but hope it helps. – cr_alberto Apr 03 '21 at 18:43
  • 1
    Isn't it already considered a module? – lino49 Apr 03 '21 at 18:54
  • Yep, sorry, you're right. I mean `utils.py` as a package itself. – cr_alberto Apr 03 '21 at 19:38
  • You mean to add it on site-packages like the packages I install with pip ? – lino49 Apr 03 '21 at 19:47
  • No, not an external package. Just create a folder named `utils`. Then place your `utils.py` file inside the new folder, and create en empty `__init__.py` file. See https://docs.python.org/3/reference/import.html#packages – cr_alberto Apr 03 '21 at 19:58

1 Answers1

0

If I'm understanding this correctly the subfile.py script is in another directory so you can't import the same way as you do in main.py you would need to do something similar to this answer so like

from ..utils import *
Garrett S
  • 111
  • 5
  • If I do this, I get a new error on the import line which is "Attempted relative import beyond top-level package" – lino49 Apr 03 '21 at 19:44