Pydev shows unresolved import, but script runs?

2020-07-02 11:50发布

问题:

I am using PyDev.

I am trying to organise my project classes into packages.

e.g. In a folder I have a module at /libraries/fund_price_library.py

In another file in my project, I try to import using:

from libraries.fund_price_library import FundPriceLibrary as fpl

PyDev underlines "FundPriceLibrary as fpl" in red, marking it with this error:

unresolved import fpl

However, my script works perfectly fine, so I believe that I am doing the import correctly.

I have lots of similar errors all over my project, and it looks messy. However, my python code works, so I assume I am importing correctly.

How do I suppress these errors?

回答1:

This question might hold the solution to your problem.

In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an init.py) to the path using that pane. Your project code will then be able to import modules from those source folders.

It might just be that PyDev doesn't know where to find the files.



回答2:

I had the same issue. Solution is (I have Eclipse 4.6 w/ Pydev 5.6):

Project > Properties > PyDev - PYTHONPATH > tab Source Folders

Do this: Add source folder (button) and add your (current) source dir, in my case it was src subdir so new item apears in the window : /${PROJECT_DIR_NAME}/src

So now I have this there:

/${PROJECT_DIR_NAME}
/${PROJECT_DIR_NAME}/src

and my PyDev is happy now :)



回答3:

Python 3 has implicit namespace packages so __init__.py files in sub packages are not mandatory. However, it seems PyDev still needs them.

My solution was to add empty __init__.py files in subpackages.



回答4:

I ran into this problem in a new project, with "unresolved import" errors an imported symbol is not actually in use yet.
It turned out to be a problem only when the eclipse "project" name and an underlying python "package" name are identical. When I changed the eclipse project name to something else, the error messages went away (seems like there might be a bug somewhere).

BTW: using Eclipse 2018-12 (4.10.0), with PyDev version 7.1.0.201902031515



回答5:

Quick and dirty solution:

Perhaps you can tell pydev to ignore the import error by using the markup UnresolvedImport in your code. See how-can-i-make-the-pydev-editor-selectively-ignore-errors for a discussion on the topic.

PS If you're using pydev in eclipse, ctrl+1 should suggest this solution.