Reputation: 823
My project has root src folder created by pydev project wizard. Src folder is in the project's python path. Underneath that folder I have a package (folder with __init__.py
) with two files: a.py
and b.py
. b.py
is trying to import from a.py
but I'm getting the error of unresolved import.
I was able to "fix" error by explicitly adding that subfolder to project's python path as additional src folder. Now I have two folders as src folders in pythonpath. What I don't understand is, why pydev is not able to resolve import since the package/folder I'm talking about is directly underneath root src folder which is in the python path. There are no python files in root src folder.
If I add __init__.py
to root src folder, the issue is still there. I simply have to add subfolder to pythonpath in order to make error go away.
Am I doing something wrong ? This doesn't seem right.
EDIT: I was wrong. My import syntax was incorrect. I should have done: from package.module import someting and not from module import something
Upvotes: 3
Views: 2500
Reputation: 365697
It's hard to tell from your description, and actual code would help, but I suspect what you're looking for is a relative import.
If you have a file pkg/a.py
that just does this:
import b
That will look for a top-level module somewhere on your sys.path
named b.py
.
But if you do this:
from . import b
Then it will look within (and only within) pkg
for a file named b.py
.
Alternatively, you could use an absolute import, the same way you would in a module outside the package, like one of these:
import pkg.b
from pkg import b
Your attempted workaround of adding pkg
to sys.path
is a very bad idea, for multiple reasons. For example, b
and pkg.b
will become different modules as far as Python is concerned, so the top-level code can end up getting run twice, you can end up with two separate copies of all of the globals (and even if you think "I'm not using globals", you probably as—classes and functions are globals, and you can easily end up with a situation where b.MyClass(3) != pkg.b.MyClass(3)
unexpectedly, which is always fun to debug…), etc.
Adding an __init__.py
to src
is also a bad idea. That turns src
into a package, meaning the proper qualified name for b
is now src.pkg.b
, rather than pkg.b
, but there's no way to import it under the proper name (unless the parent directory of src
happens to be on sys.path
as well as src
… in which case you have the exact same problem as the above paragraph).
See PEP 328 for more details, and the tutorial section on Packages for a simpler overview.
Upvotes: 3