pythonimportimport-hooks

importing same module more than once


So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:

main/
    __init__.py
    folderA/
        __init__.py
        fileA.py
        fileB.py

Really, there are about 50 more files. But that's not the point. In main/__init__.py, I have this code: from folderA.fileA import *

in folderA/__init__.py I have this code:

sys.path.append(pathToFolderA)

in folderA/fileB.py I have this code:

from fileA import *

The problem is that fileA gets imported twice. However, I only want to import it once.

The obvious way to fix this (to me atleast) is to change certain paths from path to folderA.path

But I feel like Python should not even have this error in the first place. What other workarounds are there that don't require each file to know its absolute location?


Solution

  • Don't modify sys.path this way, as it provides two ways (names) to access your modules, leading to your problem.

    Use absolute or unambiguous-relative imports instead. (The ambiguous-relative imports can be used as a last resort with older Python versions.)

    folderA/fileB.py

    from main.folderA.fileA import *   # absolute
    from .fileA import *               # unambiguous-relative
    from fileA import *                # ambiguous-relative
    

    Of course, you should be using specific names in place of that star.