absolute imports between folders - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: absolute imports between folders (/thread-28835.html) |
absolute imports between folders - mikisDW - Aug-05-2020 Hello, I'm working on a tkinter gui, and I keep having issues with imports. I've spent quite some time reading about imports, but I guess it still hasn't sunk in. My project folder is setup like so: Project/ |-- gui/ | |-- my_gui.py |-- custom_functions/ | |-- __init__.py | |-- module1.py | |-- module2.py my_gui.py uses a function in module2.py (my_function), which in turn imports a function from module1.py (parseVariable). While developping module2, I imported like this from module1 import parseVariableThis works fine in module2, but would cause import errors in my_gui.py. So what I did in my_gui.py is to add the folder "custom_functions" to my path. scriptLoc = os.path.dirname(os.path.realpath(__file__)) # add parent folder to path sys.path.append(str(Path(scriptLoc).parent)) # in this parent folder is a folder named custom_functions, add that too sys.path.append(os.path.join(scriptLoc, 'custom_functions\\')) from custom_functions.module2 import my_function...And I converted the import in module2 to from custom_functions.module1 import parseVariableThat works great, except when I now run module2 as my main script (if __name__ == '__main__') Then it would cause an import error again. So currently, when working/debugging in module2.py, i revert back to the original (from module1 import parseVariable) and after debugging I switch it back to from custom_functions.module1 import parseVariable I'm sure there is a way that this import would work in both scenario's, but I can't figure it out Any help? Thanks, Mikis sorry... it hit me that I should have typed sys.path.append(os.path.join(str(Path(scriptLoc).parent), 'custom_functions\\'))[\python] Now it works. But I still feel this is not best practice, right? [hr] sorry... it hit me that I should have typed [python]sys.path.append(os.path.join(str(Path(scriptLoc).parent), 'custom_functions\\'))Now it works. But I still feel this is not best practice, right? |