Include multiple modules on PyDev project

73 Views Asked by At

So, I want to input previously created classes in my current Python project.

For this purpose I created a folder called lib and I create one __init__.py file in it. My file structure looks like this

project_folder
    lib
        class1_folder
            class1.py
        class2_folder
            class2.py
     _init_.py
     project_script.py

In the __init__.py file located in the main project folder, I have 2 lines of code.

from class1_folder import class1
from class2_folder import class2

I want to be able to use the classes that I implemented in my project_script.py. How would I be able to call them if they are nested so deeply? In project_script, I do the following from lib.class1_folder.class1 import * But I get an ImportError: No module named class1_folder

2

There are 2 best solutions below

0
On BEST ANSWER

You need to add the __init__.py file to each folder which should be treated as a package (for your example, they should be added to class1_folder and class2_folder).

1
On

What you are trying to do is import the file class1.py, by saying import class1, what you actually need to do is import the class from within the file class1.py (may I recommend renaming your files; they make things a little confusing:) ). So, let's say, for example, that your classes are named Dog and Cat (Just to use something completely different, as to avoid confusion), you would need to use:

from class1 import Dog
from class2 import Cat

Just keep in mind though, the above only works if all of your files are in the same directory, so I would recommend keeping them all in the same directory.

One more thing, in case this is still confusing, when I'm writing "from class1 import Dog", that class1 stands for class1.py, it just doesn't have the file extension at the end. It does not stand for the actual name of the class.