Aeiddius
Aeiddius

Reputation: 378

How to import class from a folder in the same root?

I have a directory like this:

-RootFolder/
   - lib/
       - file.py
   - source/
       - book.py

I'm at the book.py, how do I import a class from the file.py?

Upvotes: 2

Views: 802

Answers (3)

Irfan wani
Irfan wani

Reputation: 5075

from lib.file import some_module

I think this should work fine if the rootfolder is added to path.

If not, we need to do that first as shown by @Amadan and @SorousH Bakhtiary (just wanted to add some explanation);

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

So here, Path(__file__) gives the path to the file where we are writing this code and .parent gives its parent directory path and so on.

Thus, str(Path(__file__).parent.parent) gives us path to the RootFolder and we are just adding that to the path.

Upvotes: 1

S.B
S.B

Reputation: 16496

When you are running book.py, only it's directory is gonna be added to the sys.path automatically. You need to make sure that the path to the RootFolder directory is in sys.path(this is where Python searches for module and packages) then you can use absolute import :

# in book.py
import sys
sys.path.insert(0, r'PATH TO \RootFolder')

from lib.file import ClassA
print(ClassA)

Since you added that directory, Python can find the lib package(namespace package, since it doesn't have __init__.py)

Upvotes: 2

Amadan
Amadan

Reputation: 198324

If you start your program from RootFolder (e.g. python -m source.book), the solution by Irfan wani should be perfectly fine. However, if not, then some hacking is required, to let Python know lib also contains relevant code:

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent / "lib"))
import file

Upvotes: 1

Related Questions