python __import__() imports from 2 different directories when same module exists in 2 locations

StackOverflow https://stackoverflow.com/questions/4601185

  •  25-09-2019
  •  | 
  •  

Question

I have a python application , which has directory structure like this.

-pythonapp
   -mainpython.py   
   -module1
      -submodule1
          -file1.py
          -file2.py

      -submodule2
           -file3.py
           -file3.py

      -submodule3
           -file1.py
           -file2.py
           -file5.py
           -file6.py
           -file7.py

when I try to import the python utilities(from mainpython.py) under submodule3 , I get the initial 2 files from submodule1.(please note that submodule1 and 3 have 2 different files with the same name). However the same import works fine when there is no conflict i.e it correctly imports file 5,6,7 from submodule3.

Here is the code :

name=os.path.splitext(os.path.split("module1\submodule3\file1.py")[1])[0] --> file1.py name here is passed dynamically. 

module = __import__(name) 

//Here is name is like "file1" it works(but with the above said issue, though, when passes the name of the file dynamically), but if I pass complete package as "module1.submodule1.file1" it fails with an ImportError saying that "no module with name file1"

Now the question is how do we tell the interpreter to use only the ones under "module1.submodule3.file2"? I am using python

This is really urgent one and I have run out of all the tries. Hope some experienced python developers can solve this for me?

Was it helpful?

Solution

Try to create packages out of your directory by having a having an empty __init__.py file in each and whenever you want to reference a particular module from a package using

from submodule import mymodule

Syntax. Creating packages are a good way to separate the modules into different namespaces. And name your modules according to its functionality, don't have them as file1, file2 etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top