Is it possible to distribute a python class into different .py files and call them to a main.py file?

32 Views Asked by At

Is this what modular programming is all about? I have recently started python intermediate programming and it's been advised to me to distribute all my functions into different files under the same class. I have tried but I'm running into various OS problems while importing. Basically it was a C.R.U.D. operation in python using sqlite3.

And so according to the above advice I need to make 5 different .py files. One for each of the operation and then a 5th one to display the database. Which means that I need to import 5 different files in my main.py file also while maintaining all the functions into a class of CRUD

So my question arises that this importing and maintaining the class doesn't that make it a hectic thing? If there is a better way to do it please advice me.

Folder structure for my program is below:

 ->services (folder)
   ->__pycache__ (folder)
   ->input_files (folder)
   ->output_files (folder)
   ->__init__.py
   ->add_crud.py
   ->read_crud.py
   ->update_crud.py
   ->delete_crud.py
   ->file_choose.py

-> __init__.py
-> crud.db
-> main.py

Thank you.

I tried importing every file into the main.py file but it always ran into trouble of could not find the file. A snippet of my import in main.py looks like this:

from services import file_choose as fc
from services import insert_crud as ic
from services import view_crud as vc
1

There are 1 best solutions below

2
ShinyHero On
from services import file_choose as fc
from services import insert_crud as ic
from services import view_crud as vc

According your snippet above,you tried import insert_crud and view_crud from services ,but there is no one file named insert_crud.py or view_crud.py in your folder structure for the moudle services bottom.

 ->services (folder)
   ->__pycache__ (folder)
   ->input_files (folder)
   ->output_files (folder)
   ->__init__.py
   ->add_crud.py
   ->read_crud.py
   ->update_crud.py
   ->delete_crud.py
   ->file_choose.py

maybe it is just a mistake,but if you want to import another package which is not in the services folder,try import it in __init__.py.