Skip to content Skip to sidebar Skip to footer

Re-importing Different Python Module With Same Name

I have a python project which needs to be able to run external scripts. These scripts are dynamically imported in a directory structure with several modules. Now, as these scripts

Solution 1:

You should be using relative imports in a.py and b.py. So, your imports should be like:

from . import utils

which means from current directory, import utils. This way you ask your python program to import a/utils.py in a/a.py and b/utils.py in b/b.py.

Firstly create a __init__.py in the directory having main.py (assuming __init__.py is alread present in a and b) and then import a and b in main.py as:

from a import a   # No need to do `sys.path.append('a')`from b import b

# For importing utils.py  (if needed)from a import utils as a_utils
a_utils.hello()

from b import utils as b_utils
b_utils.hello()

Also read:

Solution 2:

Normally, to import modules, we don't need to use sys.path:

main.py

from a import a
# first 'a' is the directory. second 'a' is a.py# the 'a' directory needs to have __init__.py which can be blankfrom b import b

a/a.py

from . import utils

b/b.py

from . import utils

Since you cannot modify the external modules, you can rename the modules that have the same names when you import them:

main.py

from a import utils as utils_a
from b import utils as utils_b

utils_a.hello()
utils_b.hello()

Post a Comment for "Re-importing Different Python Module With Same Name"