3

My end goal with my current Python project structure is to be able to do:

from module.file1 import class1
from module.file1.subfile1 import subclass1

I tried the following:

/module
    __init__.py
    file1.py: Class 1
    /file1
        __init__.py
        subfile1.py: Subclass 1
        subfile2.py: Subclass 2
    file2.py: Class 2

However, while the second import statement above works, the first one does not (tested via pip installing the root working directory). I've seen structures like this before in other libraries, so I believe it is possible. If anyone could help, I would greatly appreciate it.

0

1 Answer 1

3

This code says that module and file1 are packages, and not modules:

from module.file1 import class1
from module.file1.subfile1 import subclass1

It is incorrect to have both package (directory) file1 and module (file) file1. There should be only a package.

For the class class1 to be importable from file1, it should be placed in the __init__.py of the package.

Therefore, the structure should be modified this way:

/module
    __init__.py
    /file1
        __init__.py: Class 1
        subfile1.py: Subclass 1
        subfile2.py: Subclass 2
    file2.py: Class 2
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help!
what is the difference between modules and packages in terms of python?
@Uce It's best to read about it here: docs.python.org/3/tutorial/modules.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.