How do I fix PyDev "Undefined variable from import" errors?
I've got a Python project using PyDev in Eclipse, and PyDev keeps generating false errors for my code. I have a module settings
that defines a settings
object. I import that in module b
and assign an attribute with:
from settings import settings
settings.main = object()
In some of my code--but not all of it, statements like:
from settings import settings
print settings.main
... generate "Undefined variable from import: main" messages in the Eclipse code error pane, even though the code runs without a problem. How can I correct these?
For code in your project, the only way is adding a declaration saying that you expected that -- possibly protected by an if False
so that it doesn't execute (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected).
To overcome this there are some choices:
If it is some external module, it's possible to add it to the forced builtins
so that PyDev spawns a shell for it to obtain runtime information (see http://pydev.org/manual_101_interpreter.html for details) -- ie: mostly, PyDev will import the module in a shell and do a dir(module)
and dir
on the classes found in the module to present completions and make code analysis.
You can use Ctrl+1 (Cmd+1 for Mac) in a line with an error and PyDev will present you an option to add a comment to ignore that error.
It's possible to create a stub
module and add it to the predefined
completions (http://pydev.org/manual_101_interpreter.html also has details on that).
I'm using opencv which relies on binaries etc so I have scripts where every other line has this silly error. Python is a dynamic language so such occasions shouldn't be considered errors.
I removed these errors altogether by going to:
Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined Variable From Import -> Ignore
And that's that.
It may also be, Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Imports -> Import not found -> Ignore
The post marked as answer gives a workaround, not a solution.
This solution works for me:
Window - Preferences - PyDev - Interpreters - Python Interpreter
Forced builtins
tab New...
multiprocessing
in my case) and click OK
Not only will the error messages disappear, the module members will also be recognized.
链接地址: http://www.djcxy.com/p/67884.html