bhp
bhp

Reputation: 111

Python 2.7 cannot find module in its search path

I wanted to test the relative import model of Python 2.X

Directory tree:

exercises/
    dir1/
        dir2/
            mod.py
            dir3/
                mod2.py
                mod3.py

mod.py

import sys
print 'in dir1/dir2/mod.py'
path = [name for name in sys.path if 'Frameworks' not in name]. 
print 'Module search path of mod is:\n' + str(path)

import dir3.mod2

mod2.py

print 'in dir1/dir2/dir3/mod2.py' 
import mod3

mod3.py

print 'in dir1/dir2/dir3/mod3.py by relative import'

'mod' would import 'mod2' from 'dir3', which would then import 'mod3'. In Python 3.X, this would fail because the path to 'mod3' is not provided; in Python 2.X, the interpreter searches the same directory containing 'mod2' before searching the rest of the path starting from the top level directory of 'mod'.

This is the error message I get:

MacBook-Pro-9 exercises % python dir1/dir2/mod.py
in dir1/dir2/mod.py
Module search path of mod is:
['Users/arthur/Desktop/learning_python/exercises/dir1/dir2', '/Library/Python/2.7/site-packages']
Traceback (most recent call last):
  File "Desktop/learning_python/exercises/dir1/dir2/mod.py", line 8, in <module>
    import dir3.mod2
ImportError: No module named dir3.mod2

I know 'dir2' contains 'dir3/mod2', but for some reason, Python can't find it. I'm pretty sure that the syntax for the import statement is correct.

I modified the print statements and changed 'mod2.py' code to read from . import mod3. I edited nothing else, and it ran just fine in Python 3.8 There was no problem finding 'dir3.mod2'

Upvotes: 1

Views: 236

Answers (1)

lirivera
lirivera

Reputation: 46

You have to add an empty file inside dir3 named __init__.py for python to be able to recognize the directory as a Python package directory. If you have these files

dir3/__init__.py
dir3/mod2.py
dir3/mod3.py

You can now import the code in mod2.py and mod3.py as

import dir3.mod2
import dir3.mod3

or

from dir3 import mod2
from dir3 import mod3

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

Here is the a link.

Upvotes: 2

Related Questions