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
#2
this is still a good plan: https://docs.python-guide.org/writing/structure/
oclmedyb likes this post
Reply
#3
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.
oclmedyb likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 2,963 May-11-2020, 07:22 PM
Last Post: nboweb
  sub-folders in folders from text line jenost 1 1,567 Mar-31-2020, 07:16 AM
Last Post: ndc85430
  parent/add and child/div PyMan 1 2,409 Feb-23-2018, 04:38 PM
Last Post: nilamo
  import not working properly mepyyeti 5 4,360 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