Import the same module more than once

So, after a few hours, I discovered the cause of the error in my application. My application source is structured as follows:

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

Indeed, there are about 50 more files. But this is not the point. In main/__init__.pyI have this code:from folderA.fileA import *

in folderA/__init__.pyI have this code:

sys.path.append(pathToFolderA)

in folderA/fileB.pyI have this code:

from fileA import *

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

The obvious way to fix this (at least to me) is to change certain paths from pathtofolderA.path

But I feel that Python should not even have this error in the first place. What other workarounds exist that do not require each file to know its absolute location?

+3
2

sys.path , () , .

. ( Python.)

folderA/fileB.py

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

, .

+4
  • sys.path - , . - PYTHONPATH , Python .

  • import *. .

  • , folderA sys.path. main . : import main.folderA, import folderA - ; , .

+5

Source: https://habr.com/ru/post/1737969/


All Articles