Properly import from sub/parent 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: Properly import from sub/parent folders? (/thread-31466.html) |
Properly import from sub/parent folders? - oclmedyb - Dec-13-2020 Hello, I want to organize my project in different folders. Currently everything is in one folder but this is getting messy really fast. This is what I want: -- Project/ ---- Python/ ------ main.py ------ Modules/ -------- module1.py -------- Classes/ ---------- class1.py ---------- class2.py in module1.py I want to import class1.py in main.py I want to import module1.py I want to run main.py but I also want to run module1.py individually via CLI. I searched a lot and found many things like adding empty __init__.py files to every folder or import with "." or ".." (which should be relative imports if I understand correctly). But nothing really works. Either main.py works but then I can't run module1 indiviually, or vice versa... Is what I want even possible? Does it even make sense? How could I achieve the above? Thank you in advance! edit: I put the following in module1.py and it works now. But I am not sure if this is a proper solution. I've never seen imports like this before... if __name__ == '__main__': from Classes.class1 import * from Classes.class2 import * else: from .Classes.class1 import * from .Classes.class2 import * RE: Properly import from sub/parent folders? - Larz60+ - Dec-13-2020 this is still a good plan: https://docs.python-guide.org/writing/structure/ RE: Properly import from sub/parent folders? - snippsat - Dec-14-2020 Here are some examples here, here, here. Never write it so users has to use * ,or never use * in import at all.Look at first link there you see i lift sub-modules,to make import easier for users. This mean that all files/content of this package can be reach from one import import my_makehtml .Also this tutorial,goes trough many topic longer down there is a Making a Package link.
|