Search code examples
python-2.7pylint

Pylint disagrees with file import


In reference to How do I import a Python script from a sibling directory?, Pylint will error with E0401:Unable to import at line 6.

if __name__ == '__main__':
if __package__ is None:
    import sys
    from os import path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from components.core import my_module
else:
    from ..components.core import my_module

Is this just something that we have to accept, or is there a rigorous solution to correct this?

While the file in question is part of my unit tests and not critical to deployment, I would like to keep everything error free.

(pylint 1.6.4, Python 2.7.12)


Solution

  • If you are referring to importing components, then this would not work, since pylint does not understand modifications of sys.path. It would be theoretically feasible to understand them, but since it is a static analysis tool, it has its limitations with regard to what it can and what it should do. In order to help it, you might try running pylint with --init-hook="import sys; sys.path.append(path.dirname(path.dirname(path.abspath('your file'))))".