18

So. I'm aware that this question seems to have been asked to death, but none of the answers seem to address what I want to do.

I have a library in another directory that I want to include in a set of other projects that I run. I don't want that library added every time I run python..

So, what I had been doing was this in my python code:

import sys
sys.path.append("/tmp/demo/src/my-lib")
import MyClass

and this worked fine. But, now that I've discovered and love pylint, it complains that

E:  7, 0: Unable to import 'MyClass' (import-error)
C:  7, 0: Import "import MyClass" should be placed at the top of the module (wrong-import-position)

I know I could just disable import-error and wrong-import-position with a directive (or just by putting it into .pylintrc...) But, I'd rather not. I'd like to know the "right" way of adding a path to sys.path that's not global to all my projects, just to the subset of projects that use that particular library.

Is this possible?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
bnsh
  • 800
  • 2
  • 6
  • 20

3 Answers3

13

You can do it using an "init hook" for pylint. See this answer: https://stackoverflow.com/a/3065082/4323

And this statement from pylint's bug tracker:

We will probably not going to support this automatically. But right now we do support manually additions to path, although in a more cumbersome way, through ``--init-hook="import sys; sys.path.append(...)"

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

This is an old post but after searching for a while I couldn't really find an easy solution for my problem so perhaps this workaround can also be useful for others. Recently I experienced a similar issue when using a python linter in Visual Studio Code: every time I saved my python file in VSC the linter would place the sys.import behind the import code and therefore my modules could not be loaded.

I know it can be solved by changing PYTHONPATH etc and by changing linter config files but in my case I'm unable to change all this because the module is part of another application.

As a workaround I solved the lint errors by doing:

import sys

if 1==1:
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
    import mylib

This stopped the linter to complain and the VSC formatter to rearrange my import rules.

0

A solution on linux is to replace os.path.dirname(__file__) with $PWD in the init hook

pylint --init-hook="import sys; sys.path.append(\"$PWD/../../model\");" my_code.py

is a replacement for:

sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'model'))
StanOverflow
  • 557
  • 1
  • 5
  • 21