tituszban
tituszban

Reputation: 5152

How do I import a remote module, that imports a local module?

I have my program importing a module from a different location using importlib.
This imported module (let's call it A) imports some other custom module located next to it (let's call it B).

My_Project\
    │
    └─── my_program.py

Some_Other_Location\
    │
    ├─── A_module_my_program_wants_to_import.py
    └─── B_module_A_imports.py

When I import A without it importing B, it works just fine:

# Sample from my_program.py

path = Some_Other_Location\A_module_my_program_wants_to_import.py
spec = importlib.util.spec_from_file_location("A", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

However, when in A I import B:

# Sample from A_module_my_program_wants_to_import.py

import B_module_A_imports

Or

from B_module_A_imports import foo

And I run my program, I get:

Build error: No module named 'B_module_A_imports'
And a traceback to where I import in my program, and A

I've tried specifying submodule_search_locations=Some_Other_Location of spec_from_file_location but it didn't help.

So the question is how do I import a remote module, that imports a local module?

Upvotes: 2

Views: 501

Answers (1)

tituszban
tituszban

Reputation: 5152

I've found a workaround, not a proper solution though. The workaround is as follows:

I've realised that it's trying to load B where my_program is located and obviously didn't find anything. However, it is possible to trick the loader to find the file, by adding Some_Other_Location to sys.path. So this is what the import part of my_program looks like:

directory = Some_Other_Location
sys.path.append(directory)

path = Some_Other_Location\A_module_my_program_wants_to_import.py
spec = importlib.util.spec_from_file_location("A", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

sys.path.remove(directory)

This works just fine, however, I'm still open for actual solutions!

Upvotes: 1

Related Questions