0

Consider the following structure

├── __init__.py
├── script.py
├── lib
│   ├── __init__.py
│   ├── utils.py
│   ├── utils2.py

I know that I can import any function defined in utils.py into script.py doing from lib.utils import function. Also, I can import any function defined in utils2.py into utils.py using a relative import, i.e. from .utils2 import function2.

With time my root folder has been growing with files so that an additional organization into folders is needed, so I would like to have something like this

├── __init__.py
├── realtime
│   ├── __init__.py
│   ├── script.py
├── lib
│   ├── __init__.py
│   ├── utils.py
│   ├── utils2.py

If I attempt an import with respect to the package root in realtime/script.py now

from lib.utils import function

I get an error.

Is there any way to resolve the import always with respect to the root folder when I'm running a script inside a subfolder? I would like to avoid having all my main scripts in the root and also avoid having to insert something in syspath, which is what many solutions online are suggesting. Does Python not have an official way of dealing with this?

Droid
  • 441
  • 1
  • 3
  • 18
  • Never done this myself but [PEP 302](https://peps.python.org/pep-0302/) can be a starting point, e.g. using a [meta hook](https://peps.python.org/pep-0302/#specification-part-2-registering-hooks). – Michael Butscher Aug 01 '23 at 09:04
  • How do you execute `realtime/script.py`? If your working directory is the root of what you have shown and you run `python realtime/script.py`, the import `from lib.utils import function` should work. – mkrieger1 Aug 01 '23 at 09:05
  • Does this answer your question? [Can't import my own modules in Python](https://stackoverflow.com/questions/9383014/cant-import-my-own-modules-in-python), i.e. create a setup script and install your package so that it will be found in `sys.path`. – mkrieger1 Aug 01 '23 at 09:07
  • @mkrieger1 I do indeed execute `script.py` directly from the `realtime` folder from a bash file. But I just tried to do what you suggested and it still gave me the same error – Droid Aug 01 '23 at 09:10
  • Also check out https://stackoverflow.com/questions/35064426/when-would-the-e-editable-option-be-useful-with-pip-install – mkrieger1 Aug 01 '23 at 09:12

0 Answers0