Python Forum
Properly import from sub/parent folders?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Properly import from sub/parent folders?
#1
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 *
Reply


Messages In This Thread
Properly import from sub/parent folders? - by oclmedyb - Dec-13-2020, 05:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 3,085 May-11-2020, 07:22 PM
Last Post: nboweb
  sub-folders in folders from text line jenost 1 1,628 Mar-31-2020, 07:16 AM
Last Post: ndc85430
  parent/add and child/div PyMan 1 2,506 Feb-23-2018, 04:38 PM
Last Post: nilamo
  import not working properly mepyyeti 5 4,550 Jan-18-2018, 07:08 AM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020