2

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?

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank u @sorousH Bakhtiary and Amadan for correcting me. BTW this thing is automatically handled if we are using some framework or anything (e.g, if we are creating a backend for some app etc).
1

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 

Comments

1
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.

1 Comment

Only if the path to the parent of lib is recognizable by Python.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.