Skip to content
Advertisement

3 level chained python import is failing

I have the following folder structure across 3 levels: folder1 contains folder1_1 which again contains folder1_1_1. Now we have a .py file in each folder (besides the ‘init.py’ which is apparently needed, and sorry I don’t know how to put those 2 lines before and after).

JavaScript

File contents file1.py

JavaScript

file1_1.py

JavaScript

file1_1_1.py

JavaScript

So each file imports from the directly lower folder. One step works: When I run file1_1.py the import from file1_1_1 works fine, and it produces the desired result (2)

But the ‘2 level’ import in file1 fails:

JavaScript

How can I import in this manner? Or do I need to rearrange my folders? In the actual code this structure is quite involved with file1_1 having many import statements pointing to file1_1_1 which is actually many files. Thats why the separate subfolder (folder1_1_1) I checked multiple S.O. issues but they are all somewhat different in my estimation.

Advertisement

Answer

PEP 366 may be of interest here, but you don’t need the -m flag in this case. In your case, the only difference is the import within folder1_1/file1_1.py. I import starting from the entry name where it was run, so folder1_1 is included. You can also see more information in these answers:

The closest to your example that works is:

file tree

JavaScript

file1.py

JavaScript

folder1_1/file1_1.py

JavaScript

folder1_1/folder1_1_1/file1_1_1.py

JavaScript

Now if you run from the top folder:

JavaScript

It yields the output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement