Python : importing different module with same name

2020-04-11 08:49发布

问题:

I am working on a project that requires to have several modules with the same name. This is a representative extract of the architecture, with __init__.py files to show which folders are modules:

/path1
    /ProjectA
        __init__.py
        /src
            __init__.py
            /ctrl
                __init__.py
                somectrl.py
            ...
/path2
    /ProjectA
        __init__.py
        /src
            __init__.py
            someclass.py

And in my class someclass.py, I want to import somectrl.py like this :

from ProjectA.src.ctrl import somectrl

But the import fails: it tells me that there is no ctrl package. Seems like it just looks into ProjectA from path2, and completely ignores ProjectA from path1 ! Both path1 and path2 are in my PYTHONPATH. So can't they both be reached?

Is there a clean way out of this nasty situation?

回答1:

One way would be to use the imp module.

import imp
somectrl = imp.load_source("somectrl", "path1/ProjectA/src/ctrl/somectrl.py")
someclass = imp.load_source("someclass", "path2/ProjectA/src/someclass.py")