0

I have the below module structure:

/home/Dir1/Dir2/Mod.py

Inside /home i have the script Test.py which I am executing and has the below code :

import Dir1.Dir2 
dummy()

Again the Directory: Dir1 has an __init__.py file which has the below code:

print('dir1 init')
x = 1

The directory Dir2 has the below __init__.py file having the following code:

from Mod import dummy
print('dir2 init')
y = 2

There is a final file Mod.py which is defined as follows:

print ("in Mod.py")
z = 3
def dummy():
    print ("Hello World")

Since Test.py is the entry point in my application this is the below error I get:

dir1 init
Traceback (most recent call last):
  File "Test.py", line 1, in <module>
    import Dir1.Dir2
  File "C:\Users\bhatsubh\Desktop\Everything\Codes\Python\Dir1\Dir2\__init__.py"
, line 1, in <module>
    from Mod import dummy
ImportError: No module named 'Mod'

Why is the __init__.py file inside Dir2 not able to find the file Mod.py?

Basically what I am trying to do here is make the function dummy inside Mod.py public without the user knowing that there is a module by that name.

Am I doing something silly here?

0

1 Answer 1

0

Change your Test.py to use dummy with the fully qualified name:

import Dir1.Dir2

Dir1.Dir2.dummy()

and your Dir1/Dir2/.__init__.py to use a relative import with a leading . in front of Mod:

from .Mod import dummy
print('dir2 init')
y = 2

to make it work:

python Test.py 
dir1 init
in Mod.py
dir2 init
Hello World

Note: Per convention all package (i.e. directory) and module (i.e. py file) names should be lower case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.