0

I have

myapp/
    __init__.py
    lib.py
    tests/
        lib_test.py

In lib_test.py I have:

import lib

When running from myapp:

python tests/lib_test.py

I get an error

ImportError: No module named lib

It's some sort of beginner error no doubt. However I can't figure out what is going wrong.

2 Answers 2

5

When you try to do import lib like you have above, Python tries to find the import, starting with the directory you are in (so, for example, if you were right in the myapp directory, it would find lib.py and be able to import lib). However, when importing within a package (basically, anything with __init__.py) you should go towards using explicit package imports (like from myapp import lib) so that the python interpreter will know where to look. This also has the advantage of avoiding namespace collisions with lib (i.e., if you were in a different folder that had lib.py in it).

Bottom line: replace import lib with from myapp import lib and you'll be good.

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

1 Comment

Personally, I have a preference for relative imports: from .. import lib. This requires an __init__.py file in the tests directory.
1

You should add __init__.py file in tests/ directory.

2 Comments

Thank you for the excellent suggestion. Unfortunately I'm still getting the same error
Could you please try this "from myapp import lib" in lib_test.py file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.