0

Ive got this structure and I wish to access a function from utils while being in main.py. How can I do this without setting a path?

from utils.util import * doesn't work. Using "..utils" doesn't work either. I've run out of ideas.

enter image description here

by3by3byt3
  • 67
  • 6
  • "Using "..utils" doesn't work either." What happens when you try that? What is the current working directory when you run the code? Is `main.py` supposed to be the entry point for the program? Your problem is almost certainly a duplicate, but it's hard to know *which* is the duplicate question without having full context. – Karl Knechtel Jan 03 '22 at 20:53
  • Also: is the `app` package supposed to be usable by others, with `app.src.main` just functioning as a "driver"? Or is it supposed to be purely a standalone program? – Karl Knechtel Jan 03 '22 at 20:57
  • ..utils says "attempted relative import with no known parent package". App is just a standalone program and yes, its the main entry point. The working directory would be app/src (i ran getcwd() and thats what it showed). – by3by3byt3 Jan 03 '22 at 21:09
  • I used os.chdir(../) and the import worked. Is there a better way to do this without imoprting "os"? – by3by3byt3 Jan 03 '22 at 21:11
  • "I used os.chdir(../) and the import worked. Is there a better way to do this without imoprting "os"?" This sort of thing isn't very robust, because the current working directory could be different places. It depends on *how you are running* the program. The relative import is designed for you to run the program from *outside the package directory*. In this case, you would use the command line to navigate to the parent directory of `app`, and then run the program like `python app/src/main.py`, or possibly `python -m app.src.main`. – Karl Knechtel Jan 03 '22 at 21:15
  • But you probably should consider restructuring the project. It makes more sense to have `main.py` outside all those folders, so that you can `python main.py` from the folder that contains it, and let `main.py` import from a sub-folder. The key idea here is that Python puts the *current* directory onto the search path for modules at startup; but looking into parents is trickier. The linked duplicate has a lot more information. – Karl Knechtel Jan 03 '22 at 21:20

0 Answers0