1

I have a hierarchy of packages like this:

dir/
    subdir1/
        __init__.py
        module3.py
        module4.py
    __init__.py
    module1.py
    module2.py

There is a msg variable in module2 and module4 respectively.

I import module2 in module1, and it works:

import module2
print(module2.msg)

But when I import module4 in module3, vscode gives me the error: [pylint] E0401:Unable to import 'module4'. However, when I run it by python .\subdir1\module3.py, python interpreter doesn't complain this and run smoothly:

import module4
print(module4.msg)

enter image description here

What's the problem?

EDIT: enter image description here

4
  • you should type import subdir1.module4 , also i smell a duplicate of this somewhere. Commented Apr 15, 2018 at 16:39
  • @Abra001 I spent over 4 hours on how to import modules in python yesterday. But I still get stuck with it. As for this problem, vscode give error on that import module4, but actuallly there is no error when I run it. And when I change that line to import subdir1.module4, vscode doesn't complain error though, but when I run it, python give me error ModuleNotFoundError: No module named 'subdir1'. Please help me, is there something I messed up? Commented Apr 16, 2018 at 1:02
  • @Abra001 I added a screen shot. Commented Apr 16, 2018 at 1:11
  • the main code should be in the root dir, not in a subdir Commented Apr 16, 2018 at 13:03

1 Answer 1

1

The problem is you're executing the module directly as a file path. Python doesn't know module3 is in the subdir1 package, so it can't resolve the import. If you did python -m subdir1.module3 it will work.

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

4 Comments

Thanks very much @Brett. Could you tell me what's the problem with import module4 in module3.py? Because VScode say there is an error with it(the first picture). But actually when I run it, there is no error.
@Bicheng It's because you are not doing a relative import. Do from . import module4.
So, although import module4 can work, but I still SHOULD use from . import module4?
That will only work in Python 2 or if you are directly executing module3 which as I said you shouldn't be doing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.