Skip to content

core: load_module can reuse the wrong file when module names collide #557

Description

@avinxshKD

What happened:

core.common.utils.load_module() loads a Python file using only its basename.

So if Ianvs loads two different files with the same name, like:

examples/foo/testalgorithms/basemodel.py
examples/bar/testalgorithms/basemodel.py

the second load can still reuse the first basemodel module already present in sys.modules.

This is easy to hit here since many examples use common names like basemodel.py, accuracy.py, map.py, etc.

What you expected to happen:

Loading a module by file path should load that exact file.

Two files with the same basename but different paths should not collide.

How to reproduce it:

import os
import sys
import tempfile
from core.common import utils

root = tempfile.mkdtemp()
one = os.path.join(root, "one")
two = os.path.join(root, "two")
os.makedirs(one)
os.makedirs(two)

with open(os.path.join(one, "plugin.py"), "w") as f:
    f.write('VALUE = "one"\n')

with open(os.path.join(two, "plugin.py"), "w") as f:
    f.write('VALUE = "two"\n')

utils.load_module(os.path.join(one, "plugin.py"))
print(sys.modules["plugin"].VALUE)

utils.load_module(os.path.join(two, "plugin.py"))
print(sys.modules["plugin"].VALUE)
Actual output:
one
one

Expected output:
one
two

Anything else we need to know?:
Current code uses importlib.import_module(module_name) after temporarily adding the module directory to sys.path.

It should load by file path instead, probably with importlib.util.spec_from_file_location() and a unique module name. Also cleanup of sys.path should happen even when import fails.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions