Solonl
Solonl

Reputation: 2512

Python ModuleNotFoundError: No module named 'name', with unit test

I have production files which works fine with imports like these:

Ant.py:

from TurnDegree import TurnDegree

But during the unit test (While running: python -m unittest tests/AntTest.py), there is an error:

  File "/Users/x/Desktop/langton-python/src/Ant.py", line 1, in <module>
    from TurnDegree import TurnDegree
ModuleNotFoundError: No module named 'TurnDegree'

When I change it to below, the unit test is working, but now the production code fails:

from .TurnDegree import TurnDegree

With error:

  File "/Users/x/Desktop/langton-python/src/Ant.py", line 1, in <module>
    from .TurnDegree import TurnDegree
ImportError: attempted relative import with no known parent package

For the complete source, see: https://github.com/douma/langtons-ant-python

Upvotes: 1

Views: 2610

Answers (3)

eladgl
eladgl

Reputation: 69

Try finding which directories to save your files at so you could import it easily,

import sys, pprint
pprint.pprint(sys.path)

You should get something like that:

['C:\\Python35\\Lib\\idlelib',
'C:\\Python35',
'C:\\Python35\\DLLs',
'C:\\Python35\\lib',
'C:\\Python35\\lib\\plat-win',
'C:\\Python35\\lib\\lib-tk',
'C:\\Python35\\lib\\site-packages']

Each of these strings provides a place to put modules if you want your interpreter to find them. Even though all these will work, the site-packages directory is the best choice because it’s meant for this sort of thing. Look through your sys.path and find your site-packages directory, and save the module, then try importing, do the same thing in what ever compiler you use.

Tell me if it helped you saveing it there.

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69983

Use the following which treats a more specific exception:

try:
    from TurnDegree import TurnDegree
except (ModuleNotFoundError, ImportError):
    from .TurnDegree import TurnDegree

or

try:
    from .TurnDegree import TurnDegree
except (ModuleNotFoundError, ImportError):
    from TurnDegree import TurnDegree

It is not a good practice to use except Exception because that covers all possible exceptions. This means that if your program raise an exception different from ModuleNotFoundError or ImportError, it will run silently.

Upvotes: 2

Ahsun Ali
Ahsun Ali

Reputation: 314

You can do a try catch to handle both cases like below.

try:
    from TurnDegree import TurnDegree
except Exception as e:
    from .TurnDegree import TurnDegree

Does this help?

Upvotes: 2

Related Questions