4

I know that there are many similar questions but none of them addresses my specific problem: I have the following folder structure:

project/
 main.py
 /subDirec/
 __init__.py
 function1.py
 function2.py

I want to import function2 into function1 and call function1 from main.

In function1 I call

import subDirec.function2 

and in main:

import subDirec.function1

It works when I am calling main.py but not when I call function1.py. If I change it in function1 to:

import function2 

it works in function1 but not in main anymore.

asked Mar 9, 2021 at 15:09

1 Answer 1

5

There is one trick you can use to make this work. I don't believe this is considered to be a pythonic way, it looks to me more like a workaround. It might create problems if not properly used.

The idea is to define project and its subdirectories as modules and add the path to the root folder project to the system path.

You will need to create an empty __init__.py in project and in each subdirectories which scripts and functions you want to load somewhere else.

Then the idea is to import like this:

from folder.subDirec.function1 import function_of_interest

In every file in project, you'll have to import using the syntax from folder.subDirect.. This import is possible only if you are located in the folder above project or if project has been added to PATH.

To add the path to project to environment path you can use:

if __name__ == '__main__':
 import os
 import sys
 base_path = os.path.abspath(__file__).split('project')[0]
 sys.path.append(base_path)

You can place this code at the top of each file before the imports to functions from project.

For instance:

project/
 main.py
 __init__.py
 /subDirec/
 __init__.py
 plots.py
 utils.py

In utils.py I want to use plots.p1(), thus in utils.py I will have:

if __name__ == '__main__':
 import os
 import sys
 base_path = os.path.abspath(__file__).split('project')[0]
 sys.path.append(base_path)
from project.subDirec.plots import p1
p1()
answered Mar 9, 2021 at 15:14
Sign up to request clarification or add additional context in comments.

2 Comments

I indeed hoped for sth more pythonic but thanks!
@PeterDieter I did look for one myself.. couldn't find one. I tried everything with relative imports, but I always ran into problems + cyclic importing. This way may not be pythonic and estehtic, but works like a charm and prevents any cyclic import problem. Good luck in your search, please add a second answer if you find a different way, I'll be very interested!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.