I have the following:
Archivo1.py
|
->Archivo2.py
->Archivo3.py
( Archivo2.py
and Archivo3.py
) are in a subdirectory under Archivo1.py
)
The idea is that a function that is in Archivo1.py
calls another that is in Archivo2.py
, and that in turn imports a module that is in Archivo3.py
.
The problem is that the function inside Archivo2.py
looks for the module in Archivo1.py
, and not inArchivo3.py
The question is how to make it Archivo2
look atArchivo3
Thank you very much
edit:
I had not specified that the name of the directories can be variable, so when making the call I cannot use:
from subpaquete.Archivo3 import foo
according to the given answer, because the subpackage name is not defined.
Imports in a package are resolved based on the module that is executed as the parent. If you have a structure like this:
where your main module (entry point) is
Archivo1
to import namesArchivo3
fromArchivo
2 you should do:either
also
Another option is to use relative imports:
either
For a more detailed explanation see:
The proposed answer did not work for me, but I have solved it like this. I don't think it's the most appropriate method, but it works (always in the specific case in which one module is at the same level as the other and is called by another at a level other than these two)It is about obtaining the absolute path where the two modules involved are located, and adding it to the path:import inspect, os moduledirectory = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) import sys sys.path.append(moduledirectory)I'll leave it in case it helps someoneThis solution (the strikethrough) is not acceptable, since the scripts are called by another program, and when I make a second call, and in case of modules with the same name but different subdirectories, it causes conflicts.
The solution provided by @FJSevilla is the most correct, but my particular problem is that the subpackages can have any name, so I cannot define them in the script itself, but have to find out.
In the end this is the most acceptable solution, taken from here
Then, when calling it, I have to put the prefix: