0

I am developing a Python project and the current structure of the project looks like this:

myproject
__init.__py

contents
    - __init__.py
    - content1.py
    ...

configs
    - __init__.py
    - config.py
    ...
utils
    - __init__.py
    - helpers.py
    ..
app.py

Now If I want to access functions from config.py in the configs directory to helpers.py, I need to add these two lines in helpers.py at the top:

import sys
sys.path.append("..")

Similary I have to add these lines in py files in each directory if I want to access them. This clearly doesn't feel the right way. Is there any other way to make the absolute and relative imports cleaner and easier? Any explanation on top of it would be very very helpful

enterML
  • 2,110
  • 4
  • 26
  • 38

1 Answers1

0

First of all, there are many different ways to achieve what you are trying to do. Not all of them are clear and as easily maintainable (as you've concluded using sys.path.append("..")).

The best practice (IMO) is to import any function/class/etc that is needed elsewhere in your myproject/__init__.py.

For example:

myproject/__init__.py

from configs import my_config_func

Then...

myproject/utils/helpers.py

from .. import my_config_func
noslenkwah
  • 1,702
  • 1
  • 17
  • 26